循环通过json对象

时间:2014-03-19 17:57:22

标签: javascript php jquery ajax json

我一直在找一个星期而且我找不到这种情况的答案。

我通过jsonp请求数据。

$.ajax({
  type:'GET',
  dataType: "jsonp",
  url: "http://www.domain.com/app/loadFeedsApp.php", 
  sync: true,                 
  contentType: "application/json", 
  dataType: 'jsonp',                
  success: function(data) {                     
    console.log(data);
  }
});

在我的服务器端,我发送了这样的信息:

$jarr = array();
$af = 0;
while( $row = mysql_fetch_array($result) )
{
    $html = array("Appfeed".$af."" => array(
        "cnty" => stripcslashes($row['cnty']),
        "feed" => stripslashes($row['feed']),
        "feedId" => stripslashes($row['feedId']),
        "nickname" => stripslashes($row['nickname']),
        "state" => str_replace("\r\n",'', $row['state']),
        "date" => date("d/m/y", strtotime($row['date'])))               
    ); 
array_push($jarr, $html);    
$af++;
}
echo $_GET['callback'] . '(' . json_encode($jarr) . ');';

它返回数据:

jQuery21007744578921701759_1395250905357({
"Appfeed0":
{
"cnty":"MEXICO",
"feed":"text",
"feedId":"201",
"nickname":"chaparra",
"state":"Tamaulipas",
"date":"27\/02\/14"
}
});

jQuery21007744578921701759_1395250905357({
"Appfeed1":
{
" cnty ":"MEXICO",
"feed":"text ",
"feedsId":"198",
"nickname":"estudiante",
" state ":"Tamaulipas",
"date":"26\/02\/14"
}
});

jQuery21007744578921701759_1395250905357({
"Appfeed2":
{
" cnty ":"MEXICO",
"feed":"text ",
"feedsId":"197",
"nickname":"el roger",
" state ":"Tamaulipas",
"date":"26\/02\/14"
}
});

但是当我尝试在java脚本中循环显示它时,它只显示最后一个Feed(Appfeed2)。当我在console.log()中打印数据时。它看起来就像刚收到最后一个饲料。

Object {Appfeed2: Object}
1.  Appfeed2: Object
1.  state: "Tamaulipas"
2.  date: "26/02/14"
3.  feed: "Ayer fui a sacar mi licencia, sin saber manejar, no hice fila y solo me costo 200 pesos mas. Creo que sere taxista "
4.  feedId: "197"
5.  nickname: "el roger"
6.  cnty: "MEXICO"
7.  __proto__: Object
2.  __proto__: Object

有什么想法吗?我正在考虑jsonp返回数据的方式,所以我尝试使用方括号,使用和没有get回调,但它失败了。

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

你需要确保在你的PHP代码中,你只是在循环结束后回显出JSON(P)一次。您需要构建所需的数组,然后在最后回显它。

$jarr = array();
$af = 0;
while( $row = mysql_fetch_array($result) )
{
    $jarr["Appfeed".$af] = array(
        "cnty" => stripcslashes($row['cnty']),
        "feed" => stripslashes($row['feed']),
        "feedId" => stripslashes($row['feedId']),
        "nickname" => stripslashes($row['nickname']),
        "state" => str_replace("\r\n",'', $row['state']),
        "date" => date("d/m/y", strtotime($row['date'])))               
    );  
    $af++;
}
echo $_GET['callback'] . '(' . json_encode($jarr) . ');';

P.S。你的AJAX调用有太多选择:

$.ajax({
    type:'GET',
    dataType: "jsonp",
    url: "http://www.domain.com/app/loadFeedsApp.php",                
    success: function(data) {                     
        $.each(data, function(i, v){
            console.log(i);
            console.log(v);
        });
    }
});