javascript - 意外的标记 {

标签 javascript jquery ajax json

我正在向服务器上的 php 脚本发送 AJAX post 请求,服务器返回 JSON 格式的数据。当我尝试提醒结果时,出现以下错误:Uncaught SyntaxError: uncaught SyntaxError: uncaught 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":""}

为什么返回的数据没有正确提醒?非常感谢任何帮助!

最佳答案

您在一个循环中回显 JSON 字符串,最终得到一个由较短的 JSON 字符串组成的长无效字符串。

您必须对其进行编码并回显一次

$result = array();

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

echo json_encode($result);

关于javascript - 意外的标记 {,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29590353/

相关文章:

javascript - Javascript : Setting Value to the Object by id,,其中 id 是对象的最后一个字母

javascript - 查找具有特定键值对的 JS 对象/哈希

javascript - 隐藏元素并根据下拉选择不需要它们

jquery - 为什么我们在 jquery 中使用 $(document) 而不是 $ ("document") ?

javascript - 向动态表添加一个 <tr> 元素,动态地无需刷新页面,php jquery

jquery - 如何创建自定义 "confirm"并暂停 js 执行直到用户单击按钮?

javascript - 我试图让 "more"按钮显示附加信息而不加载整个页面

javascript - focus() input element with jQuery, but the cursor doesn't appear

javascript - Jquery On Paste 无法验证输入字段

javascript - 未封闭的 SVG 路径似乎已封闭