无法通过jquery从php文件中读取json传递

时间:2013-07-26 07:43:59

标签: jquery json

  [{
      p_date: "26-07-2013",
      c_no: "1",
      time_slot: "shift1"
  }]

   $.each(data, function (i, elem) {


      alert(elem[p_date]);

  }); 

我从我的php文件中获取json。我想要做的是从jquery文件中读取它。我尝试了上面的方法来读取json。但它没有用。

      i get the following error Uncaught SyntaxError: Unexpected token p 

2 个答案:

答案 0 :(得分:5)

每项功能中elem[p_date]不应该elem["p_date"]吗?或者您也可以尝试elem.p_date

 var data = [{
     p_date: "26-07-2013",
     c_no: "1",
     time_slot: "shift1"
 }]

 $.each(data, function (i, elem) {
     alert(elem["p_date"]);
     //or elem.p_date would also work.
 });

演示:http://jsfiddle.net/hungerpain/c46br/

修改:

如果收到以下错误消息,

  

无法使用'in'运算符在[{p_date:“26-07-2013”​​,c_no:“1”,time_slot:“shift1”}中搜索'77'}

这意味着你的(所谓的)JSON是一个字符串。你必须这样做:

var formatted = JSON.parse(data);

然后,您可以在formatted中使用each变量:

$.each(formatted, function (i, elem) {

PHP格式

这就是你在PHP中创建数组的方法:

$first = true;
$json = array();
while ($row = mysqli_fetch_array($distributor_List)) {
  array_push($json, $row);
}
echo json_encode($json) 

这将确保您不需要在JS中使用JSON.parse:)

答案 1 :(得分:0)

试试这个

$.each(data, function (i, elem) {
     alert(elem['p_date']); //notice the `''`
});