0

出于某种原因,我无法让John Resig 微模板工作。我读过这里,并且可以让这个例子工作,但它是一个非常简单的对象。(即var data = { fname : "fred" };),但是,当我尝试使用我更复杂的对象时

{"order":{"name":"TRADEMARK WHEEL COMPANY","sales_order_id":"18278","order_date":"05 \u2044 15 \u2044 2012","due_date":"05 \u2044 21 \u2044 2012","order_number":"1213140","reference":"21192D\/35546","order_description":"BICICLETTE","ship_name":"ADAMS","ship_address1":"1919 W RANDOLPH ST.","ship_address2":"","ship_city":"CHICAGO","ship_state":"IL","ship_postal_code":"60606","ship_country":null,"ship_via":"FEDEX GROUND","tracking_number":null,"package_contents":null,"freight":"0.00","taxable":"0.00","nontaxable":"748.88","sales_tax":"0.00"},"line_item":[{"description":"RED ONE","quantity":"2.00","sell_price":"349.44"},{"description":"FRONT GEAR","quantity":"2.00","sell_price":"15.00"},{"description":"5th GEAR","quantity":"2.00","sell_price":"10.00"}]}

并尝试像这样访问它

<script>
(function () {

  var submitStr="test string of data";

  $.ajax({
    type: "POST",
    url: "getJSON.php",
    data: submitStr,
    success: function (data) {
    console.log(data);
    var generatedText = tmpl("order_detail", data);
    var elem = document.getElementById("elemId");
    elem.innerHTML = generatedText;
    }
    });

}());
</script>
<script id="order_detail" type="text/html">
        <div>
Name:<%=data.order.name%> ID:<%=data.order.sales_order_id%><hr/>

<%for(var i=0;i<data.line_item.length;i++) {%>

      description: <%= data.line_item[i].description %><br/>
      quantity: <%= data.line_item[i].quantity %><br/>
      price: <%= data.line_item[i].sell_price %><hr/>


<%}%>
</div> 

 </script> 

我得到data未定义的错误。我已经尝试过data.,只是尝试直接访问对象的值,但这也不起作用。

我很感激使用这个东西的任何帮助!

4

1 回答 1

1

1.在$.ajax成功回调success: function (data)中,您将获得dataJSON 字符串,您必须先将其解析为对象,然后再将其传递给tmpl函数。

$.ajax({
    type: "POST",
    url: "getJSON.php",
    data: submitStr,
    success: function (data) {
        console.log(data);

        data = JSON.parse(data);

        var generatedText = tmpl("order_detail", data);
        var elem = document.getElementById("elemId");
        elem.innerHTML = generatedText;
    }
});

2.删除模板中的所有data前缀。

于 2012-05-23T17:34:38.400 回答