为什么返回的数据没有得到正确的警告?

我在向服务器上的php脚本发送Ajax POST请求,然后服务器以JSON格式返回数据。但当我试图alert结果时,我会得到以下错误:Uncaught SyntaxError: unexpected token {——两次。

这里是我的Ajax调用:

var articles = $.post("process/get_articles.php");
    articles.done(function(data){
        var result = $.parseJSON(data);
        alert(result);
    });

我的服务器端代码:

while($query->fetch()){
    $result = array("ID"=>$Art_number, "Article"=>$Article, "Image"=>$Image_link);
    $result = json_encode($result);
    echo $result;
}

返回以下内容:

{"ID":1,"Article":"Article 1","Image":"http:\/\/wwww.mydomain.com\/images\/img.jpg"}{"ID":2,"Article":"Article2","Image":""}{"ID":3,"Article":"Article 3","Image":""}

为什么返回的数据没有得到正确的警告?任何帮助都将不胜感激!

Your code is spitting out successive JSON objects back-to-back. The result, overall, is not valid JSON.

Put your arrays in an enclosing single array and then JSON-encode that as the response. That'll result in the client getting an array of objects, which will be valid.

You're echoing the JSON strings inside a loop, and you end up with a long invalid string made up of shorter JSON strings.

You have to encode and echo it once

$result = array();

while($query->fetch()){
    $result[] = array("ID"=>$Art_number, "Article"=>$Article, "Image"=>$Image_link);
}

echo json_encode($result);

More objects just one after the other are not valid JSON. Your parser complains about the start of the second object, which is completely OK. Wrap the objects into an array and it should work.

$array = array();

while($query->fetch())
    $array[] = array("ID"=>$Art_number, "Article"=>$Article, "Image"=>$Image_link);

echo json_encode($array);