处理返回JSON对象数组的Ajax响应

时间:2016-06-05 12:29:36

标签: javascript php jquery ajax

我有一个AJAX,它用一个间隔更新自己并从SELECT PHP返回数据。它返回一个包含多个元素的数组,但我不知道如何访问各个元素。我想使用它,因为我需要在我的网页上显示刷新的项目和其他不同的值。

AJAX代码:

var a=0;
setInterval(function() {
    $.ajax({
        url: "http://localhost/Seyroku/extras/mostrarBote.php",
        dataType: "jsonp",
        jsonp: "callback",
        data: {"a": "a"},
        success: function (respJSON) {
            //I usually use this to access the properties of the object but doesn't work
            var ItemName = respJSON.itemName;
            console.log(ItemName);
        }
    });
}, 5000);

mostrarBote.php代码:

$sql="SELECT  itemName, itemPrice, itemUrl, nameUser, color FROM potitems";

$result=mysqli_query($conn, $sql);
$numero = mysqli_num_rows($result);

$num=1;
if ($result!=NULL) {
    if (mysqli_num_rows($result)>0) {
        while($row=mysqli_fetch_array($result)) {
            $resposta = '{"itemName":"'.$row['itemName'].'","itemPrice":"'.$row['itemPrice'].'","itemUrl":"'.$row['itemUrl'].'"}';

            if (isset($_GET['callback'])) {
                echo $_GET['callback'].'('. $resposta.')';
            } else {
                echo ($resposta); 
            }
        }
    } else {
    }
    mysqli_free_result($result);
}

AJAX返回此响应(来自控制台输出):

  

jQuery21404145154874458823_1465128123711({" itemName":" Sticker | wayLander | MLG Columbus 2016"," itemPrice"       :" 0.33"" itemUrl":" http://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtW       wKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXQ9QVcJY8gulReQ0DFSua4xJ2DAgs7Ng1Qia2kMgth3ffNY3MXtd3uwteJlvKjN-KHxDsGvMYl2byYrNrxjQ3n80Q-Nzz2JIaWIQ5rfxiOrWILvkNz"       })jQuery21404145154874458823_1465128123711({" itemName":" Shadow Case"," itemPrice":" 0.03"," itemUrl&#34 ;:" HTTP       ://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo       4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FF4u1qubIW4Su4mzxYHbzqGtZ-KGlz8EuJcg3rnE9NiijVe3_UY-Zzr2JJjVLFEEeiQRtg"       })jQuery21404145154874458823_1465128123711({" itemName":" Revolver Case"," itemPrice":" 0.03"," itemUrl&#34 ;:" HTTP       ://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo       4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFYwnfKfcG9HvN7iktaOkqD1auLTxD5SvZYgiLvFpo7xjVLh-kdrYWnzcoGLMlhpsyM-5vg"       })jQuery21404145154874458823_1465128123711({" itemName":" Five-SeveN | Forest Night(破损不堪)"," itemPrice"       :" 0.03"" itemUrl":" http://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtW       wKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgposLOzLhRlxfbGTjVb09q5hoWYg8j6OrzZglRc7cF4n-SP9o2gjQbhqRVla2GnJ46VIQA_ZlyD-VHvxuu808S7tc7NzXFm7iUh4mGdwULQPtyarQ"       })

如何从JSON元素访问属性ItemName,ItemPrice和ItemUrl?

1 个答案:

答案 0 :(得分:0)

您的Ajax调用配置为使用'jsonp'而不是'json',它不会为您提供您想要/期望的结果。您应该将dataType选项更改为'json',然后删除jsonp选项(无论如何都会被忽略)。

您应该能够使用jQuery.each来处理Ajax success回调中JSON数组的每个元素。这样您就可以按预期访问ItemNameItemPriceItemUrl

以下是更新的Ajax代码:

setInterval(function() {
    $.ajax({
        url: "http://localhost/Seyroku/extras/mostrarBote.php",
        dataType: "jsonp",
        jsonp: "callback",
        data: {"a": "a"},
        success: function (respJSON) {
            $.each(respJSON, function(index, item) {
                var itemName = item.itemName;
                var itemPrice = item.itemPrice;
                var itemUrl = item.itemUrl;
                console.log("JSON array[", index, "]: ItemName=", itemName, " ItemPrice=", itemPrice, " ItemUrl=", itemUrl);
                //TODO: Do something useful with itemName, itemPrice, and itemUrl here
            });
        }
    });
}, 5000);