从jsonp返回值

时间:2014-01-03 17:42:46

标签: javascript html

刚学习javascript& HTML

我想从一些jsonp中获取一个值。这就是返回的内容

detail( {
"StatusCode": 0,
"StatusInfo": "Processed and Logged OK",
"PageNumber": 1,
"TotalPageCount": 1,
"TotalProductCount": 1,
"PageProductCount": 1,
"Products":
[
{
"BaseProductId": "57543094",
"EANBarcode": "5010204736716",
"CheaperAlternativeProductId": "",
"HealthierAlternativeProductId": "",
"ImagePath": "http://img.tesco.com/Groceries/pi/716/5010204736716/IDShot_90x90.jpg",
"MaximumPurchaseQuantity": 99,
"Name": "Tesco Bacon   Leek Quiche 400G",
"OfferPromotion": "Any 2 for £4.00",
"OfferValidity": "valid from 2/1/2014 until 21/1/2014",
"OfferLabelImagePath": "http://www.tesco.com/Groceries/UIAssets/I/Sites/Retail/Superstore/Online/Product/pos/2for.png",
"ShelfCategory": "134",
"ShelfCategoryName": "Pies Quiche & Pasties",
"Price": 2.3,
"PriceDescription": "£0.58 each",
"ProductId": "255163145",
"ProductType": "QuantityOnlyProduct",
"UnitPrice": 0.575,
"UnitType": "100g"
}
]
} )

我的代码如下:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tesco JSONP</title>
</head>
<body>

    <button id="detail">detail</button>

    <script type="text/javascript">

    function detail(data) {
            document.getElementById('name').innerHTML = (data.Products.Name)
        }



            function data() {
            var script_elem = document.createElement('script'),
                url = "http://www.techfortesco.com/groceryapi_b1/restservice.aspx?command=PRODUCTSEARCH&JSONP=detail&searchtext=5010204736716&page=1&sessionkey=123456789"
            script_elem.setAttribute('src', url);
            document.head.appendChild(script_elem);

        }


        document.getElementById('detail').addEventListener('click', data, false);

    </script>


    <div id="name"></div>

</body>
</html>

运行时我未定义。我猜我的语法(data.Products.Name)不正确。如果我尝试(data.StatusCode),那么我得到正确的结果。

有人可以提供建议吗。

祝福。

1 个答案:

答案 0 :(得分:1)

data.Products是一个数组。

您需要指定要在数组中访问哪个元素。

在这种情况下,您只有一个元素,因此正确的语法是data.Products [0] .name