【问题标题】:SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data what is wrong here?SyntaxError:JSON.parse:JSON 数据后出现意外的非空白字符这里有什么问题?
【发布时间】:2014-02-16 17:38:11
【问题描述】:

我已经搜索了那个错误并查找了很多帖子..但我仍然无法弄清楚这段代码有什么问题:

我的 ajax 调用:

function myCall3() {
  $.ajax({
    type:"POST",
    url:"ajax3.php",
    dataType:"json",
    success:function(response){
      alert(response[0]);
    }
  });
}

我的 mysql/php 代码:

<?php


// QUERY NEW VINE
$array = array();
$myquery = "SELECT * FROM table1 ORDER BY rand() LIMIT 9";
$result = mysql_query($myquery)
OR die("Error: $myquery <br>".mysql_error());

while($row = mysql_fetch_object($result)){
  $currentid = "$row->id";
  $currentname = "$row->name";
  $currenturl = "$row->url";
  $currentimage = "$row->image";
  $array[] =     array('id'=>$currentid,'url'=>$currenturl,'name'=>$currentname,'image'=>$currentimage);

}

echo json_encode($array);

?>

当我警告它说的错误时:

SyntaxError: SyntaxError: JSON.parse: 意外字符

【问题讨论】:

    标签: php mysql ajax json


    【解决方案1】:

    你一直在循环中覆盖 $array,然后过早地回显它。

    $array =    array('id'=>$currentid,'url'=>$currenturl,'name'=>$currentname,'image'=>$currentimage);
    
    echo json_encode($array);
    
    }
    

    您应该将每一行推送到 $array 变量,然后在循环外进行 json_encode。

    $array = array();
    $myquery = "SELECT * FROM table1 ORDER BY rand() LIMIT 9";
    $result = mysql_query($myquery)
    OR die("Error: $myquery <br>".mysql_error());
    while($row = mysql_fetch_object($result))
    {
    $currentid = "$row->id";
    $currentname = "$row->name";
    $currenturl = "$row->url";
    $currentimage = "$row->image";
    $array[] =  array('id'=>$currentid,'url'=>$currenturl,'name'=>$currentname,'image'=>$currentimage);
    
    }
    
    echo json_encode($array);
    

    那么你的 javascript 回调将需要一个数组,而不是一个对象,即

    console.log(response[0]);
    

    注意:你可以直接将 $row 推送到你想要的 $array 上。

    【讨论】:

    • 当我使用这段代码时,例如,我如何提醒所有 js 中的 url?我只是产生错误-.-
    • 什么错误?当您记录响应和响应 [0] 时会得到什么?在这一点上,它应该只是简单的数组/对象表示法。
    • 当我记录 response[0] 时它说: SyntaxError: JSON.parse: unexpected character
    • 那么响应呢?如果必须,请从头开始。这是基本调试 101。您在开发人员工具中看到了什么?它是有效的 JSON 吗? (使用 jsonlint.com)
    • 谢谢!我还在学习..很多我不知道的东西。但是你帮了我很多。终于弄明白了。谢谢!
    【解决方案2】:
    $newArray = array();
    while($row = mysql_fetch_object($result) {
       $newArray[] = $row;
    }
    echo json_encode($newArray);
    

    然后,在 JS 中你必须遍历数组。

    【讨论】:

      【解决方案3】:

      您的输出如下所示:

      {"id":123,"url":"http://.../","name":"Blah","image":"blah.png"}{"id":456,.....
      

      这对我来说看起来不对:p

      看起来你的 JavaScript 只需要一行,所以试试LIMIT 1

      【讨论】:

      • 是的,它与limit1一起工作,但问题是我想得到9 :)..我可能需要在ajax调用中将变量更改为数组吗?
      • @marc 将结果收集到一个数组中,并立即对其进行字符串化和回显。
      猜你喜欢
      • 2011-10-09
      • 2018-02-16
      • 2011-11-26
      • 1970-01-01
      • 2018-04-25
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      相关资源
      最近更新 更多