dongyi6543
2013-09-19 20:10
浏览 172

如何从responsetext获取JSON字符串到JavaScript

so I've tried this for the entire day but can't seem to solve it.. I have some AJAX getting a JSON string from a PHP script, and now I want to get it into JavaScript.

What I've tried is this:

var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    var obj = jQuery.parseJSON(xmlhttp.responseText);

    }
}
xmlhttp.open("GET","back.php?q="+query,true);
xmlhttp.send();

But all I get is

Uncaught SyntaxError: Unexpected token < x.extend.parseJSON xmlhttp.onreadystatechange

I've tried all type of code like

obj = JSON.parse(xmlhttp.responseText);
alert(obj.length);

Whatever I do I basically get the error above.. don't know what to do.. I really wanna solve this with jQuery/JS..

Thanks alot for any help!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duangua5308 2013-09-19 20:15
    已采纳

    With jquery you can just:

    $.ajax({
        url: "back.php?q="+query,
        dataType: "json",
        success: function(response) {
            alert(response.length);
        }
    });
    
    已采纳该答案
    打赏 评论
  • dpwfh874876 2013-09-19 20:17

    simply do...

    url='your/url/to/the/file.php';
    $.getJSON(url,
            function(data){
              alert(data);
              });
            });
    
    打赏 评论

相关推荐 更多相似问题