【发布时间】:2011-12-19 05:57:24
【问题描述】:
所以我有两个文件:index.php 和 query.php。
问题是,我不知道如何使用ajax 检索到的数组(msg.d)。我的数组的输出是:
{"s":0,"d":[{"userPostID":"1","userID":"1","postID":"1","choice":"1"},{"userPostID":"2","userID":"1","postID":"2","choice":"0"},{"userPostID":"3","userID":"1","postID":"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