du5739 2016-12-09 14:43
浏览 101
已采纳

JSON中的引号抛出jQuery错误,即使它们被转义

I'm using PHP to fetch JSON stored in a MySQL database, put it into a PHP variable, and pass it to JQuery, which writes the content to the page:

data = $.parseJSON('<?=$my_json;?>'); 
$.each(data.links, function(entryIndex, entry) {
    //do some stuff here
        });

Everything works fine when the JSON looks like this:

{
    "links": [{
        "url": "http://domain1.com",
        "title": "Title 1",
        "description": "This is an example for my question on Stack Overflow"
    }, {
        "url": "http://domain2.com",
        "title": "Title 2",
        "description": "This is another example for my question on Stack Overflow"
    }, {
        "url": "http://domain3.com",
        "title": "Title 3",
        "description": "This is a third example for my question on Stack Overflow"
    }]
}

But when the JSON content includes quotes, I get an error reading "Uncaught SyntaxError: Unexpected end of JSON input," even though the quotes are escaped, like this:

{
    "links": [{
        "url": "http://domain1.com",
        "title": "Title 1",
        "description": "This is an \"example\" for my question on Stack Overflow"
    }, {
        "url": "http://domain2.com",
        "title": "Title 2",
        "description": "This is another \"example\" for my question on Stack Overflow"
    }, {
        "url": "http://domain3.com",
        "title": "Title 3",
        "description": "This is a third \"example\" for my question on Stack Overflow"
    }]
}

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • dongyin2390 2016-12-09 15:12
    关注
    data = $.parseJSON('<?=$my_json;?>');
    

    The thing you're doing here is you're trying to wrap up the JavaScript object around quotes and passing it as a string to $.parseJSON function.

    This function only parses JSON string which is a string should be formed with JSON structure and that will then converted to a JavaScript object by the function.

    While $my_json variable already has a JavaScript object, you don't need to use $.parseJSON function. You can just assign it to the JavaScript variable like the following one:

    data = <?= $my_json ?>; 
    $.each(data.links, function(entryIndex, entry) {
        //do some stuff here
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改