【问题标题】:jQuery AJAX how to use the object array?jQuery AJAX 如何使用对象数组?
【发布时间】:2011-12-19 05:57:24
【问题描述】:

所以我有两个文件: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 )){
?>

查询.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));
}
?>

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

【问题讨论】:

  • 只是一个建议,您不应该在客户端存储用户 ID 并将其发送到服务器。将其存储在会话中,并在没有查询字符串的情况下发出请求。我这样说是因为考虑到我在 Dragonfly 或(我认为可能在)FireBug 中加载您的页面并将代码更改为:var userID = 1234;,现在我看到了用户 1234 的数据。也许我误解了,但如果这是生产代码,你应该认真重新考虑这种方法。
  • 你是绝对正确的。我会解决这个问题。
  • 问题已修复。现在在服务器端调用 userID。虽然提出了新问题.. 请参阅我的问题中我的代码下方的段落。
  • 您是否在控制台中遇到任何错误?另外,能否在浏览器中调试一下obj是否设置正确?
  • 尝试在$.each() 之前添加console.log(msg);console.log(obj);,看看它们会返回什么。它可能没有被正确解析或者没有被正确发送。

标签: jquery ajax arrays json loops


【解决方案1】:

试试这样的:

您需要解析成功时的响应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.");
            }
        });

【讨论】:

  • 我收到一个错误:对服务器端的调用失败。对于 query.php,Firebug 在 POST 选项卡下显示 JSON:没有子对象,但显示 SOURCE:user=1。查询。
  • 如果我从 yu 代码中删除行 contentType: "application/json; charset=utf-8", query.php 工作正常,但其余的 ajax 代码不起作用(说$.parseJSON 不是函数)。
【解决方案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 对象,即使在错误期间也是如此。该对象有一个状态部分,所以你知道发生了什么,还有一个数据部分,所以你可以返回信息。对于状态,0 始终是成功,1 始终是错误,但您可以将其他数字用于不同的结果,例如不返回任何记录。这使您可以使您的应用程序更加健壮。

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

【讨论】:

  • 阵列运行良好!事情是那个错误!弹出。我认为我是正确的,因为在 query.php 中状态的值没有设置为 0。我把 $rtrn['s'] = 0;就在while循环之上?这似乎可以解决问题。最后,如果我要使用 msg 中的值,那么适当的形式是 msg[0][choice] 吗?
  • @Jonathan 你是绝对正确的。我忘了补充。我已经更新了我的答案。关于获取数据,您可以使用msg.d[0] 获取第一行。在那之后,我不能 100% 确定是 msg.d[0]['colname'] 还是 msg.d[0].colname。这取决于 MySQL 数组是如何获得 JSON 的。如果您看到类似"d":[{"col1":val,"col2":val2},{"col1":val3,"col2":val4}] 的内容(即对象数组),那么您可以使用第二个选项(msg.d[0].colname)。就个人而言,我喜欢 JSON 就是因为这个原因,因为它使代码更具可读性和易于理解。
  • 我不想打扰...我已经确定正确的格式是 msg.d[#]['field']。我不知道如何遍历数组,以便 while i
  • @Jonathan 您能否发布一个 query.php 输出的示例。此外,这可能值得提出一个新问题。
  • 我为自己感到非常自豪——我想通了!看我的回答。
【解决方案3】:

我想通了!

<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>

【讨论】:

  • 谁一直拒绝投票给我的帖子?此方法有效,如果您知道得更好,请与公众分享,否则请不要成为巨魔!
猜你喜欢
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多