jQuery AJAX如何使用对象数组?

时间:2011-11-01 05:15:53

标签: jquery ajax arrays json loops

所以我有两个文件:index.php和query.php。

问题是,我不知道如何使用ajax检索的数组(msg.d)。我的数组的输出是:

{"s":0,"d":[{"userPostID":"1","userID":"1","postID":"1","choice":"1"},{"userPostI‌​D":"2","userID":"1","postID":"2","choice":"0"},{"userPostID":"3","userID":"1","pos‌​tID":"3","choice":"1"}]}

我想要做的是遍历数组以便

while (i < array.length){ 
      if (msg.d[i]['choice'] = 1) {
           //do something with msg.d[i]['postID']
      } else if (msg.d[i]['choice'] = 0) {
           //do something else with msg.d[i]['postID']
      }
      i++
}

我从来没有使用过对象数组之前和之后我可以收集的东西,我想要做的事情是相当复杂的,我无法弄清楚我找到的例子。

index.php

<script type="text/javascript">
$(document).ready(function() {
// set $checked values

    $.ajax({
        url: 'query.php',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (msg) {
                console.log(msg);
                },
        error: function (x, e) {
            alert("The call to the server side failed.");
        }
    });
});
</script>

<?php
$data = mysql_query("SELECT * FROM Posts LEFT JOIN userPosts ON Posts.postID = userPosts.postID AND userPosts.userID = $userID") or die(mysql_error());

while($row = mysql_fetch_array( $data )){
?>

query.php

<?php

$query = mysql_query("SELECT * FROM userPosts WHERE userPosts.userID = $userID") or die(mysql_error());

if (mysql_num_rows($query) == 0)
{
echo 'error';
}
else
{

echo json_encode(mysql_fetch_assoc($query));
}
?>

我知道,我很接近...... 没有错误!

3 个答案:

答案 0 :(得分:2)

我认为你想要做的是将整个记录集提取到一个数组中,然后将其作为JSON传递给客户端。现在,您只需拨打mysql_fetch_assoc一次。这意味着你只能获得第一行。

我设置它的方式是这样的(注意 - 我还没有测试过这段代码):

<强> query.php

<?php
$query = mysql_query("SELECT * FROM userPosts WHERE userPosts.userID = $userID");

// Return array contents:
// s = Status value, d = Data
// s == 0 -> Success
// s == 1 -> Error
// s == 2 -> No rows returned
$rtrn = array('s' => 1, 'd' => array());
//Check for error
if (mysql_errno() == 0) {
    //Check for no rows returned
    if (mysql_num_rows($query) == 0) {
        $rtrn['s'] = 2;
    } else {
        //Set status value to 0
        $rtrn['s'] = 0;
        //Get all rows from the query
        while($row = mysql_fetch_array($query)){
            //Append row to the data array
            $rtrn['d'][] = $row;
        }
    }
}
//Echo the return array
echo json_encode($rtrn);
?>

index.php(仅限成功回调)

success: function (msg) {
    if (msg.s == 0) {
        //Loop through returned data array using: msg.d
        //For example: msg.d[0] is the first row.
    } else if (msg.s == 2) {
        alert('No rows returned!');
    } else {
        alert('Error!');
    }
},

基本上,我在这里做的是确保始终返回JSON对象,即使在出错时也是如此。该对象具有状态部分,因此您知道发生了什么,以及数据部分,因此您可以返回信息。对于状态,零总是成功,一个总是错误,但您可以使用其他数字表示不同的结果,例如没有返回记录。这使您可以使应用程序更加健壮。

如果其中任何一项工作不正常,请告诉我,因为正如我所说,我还没有测试过。

答案 1 :(得分:0)

尝试这样的事情:

您需要解析成功http://api.jquery.com/jQuery.parseJSON/

的回复

然后遍历它http://api.jquery.com/jQuery.each/

$.ajax(
        {
            type: "POST",
            url: 'query.php',
            data: 'userID=' + userID,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                var obj = $.parseJSON(msg);
                    $.each(obj, function(i, val) {
                        alert(JSON.stringify(val));
                    });
            },
            error: function (x, e) {
                alert("The call to the server side failed.");
            }
        });

答案 2 :(得分:-1)

我已经弄清楚了!

<script type="text/javascript">
$(document).ready(function() {
// set $checked values

    $.ajax({
        url: 'query.php',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (msg) {
                if (msg.s == 0) {
                    //Loop through returned data array using: msg.d
                    for (var key in msg.d) {
                        var obj = msg.d[key];
                        for (var prop in obj) {
                            if (prop == "postID"){
                                if (obj['choice'] == 1){
                                //do something with liked posts.
                                } else if (obj['choice'] == 0){
                                //do something with disliked posts.
                                }
                            }
                        }
                    }
                } else if (msg.s == 2) {
                    alert('No rows returned!');
                } else {
                    alert('Error!');
                }
            },
        });
    });
</script>