2011-05-06 82 views
2

我有这样的代码如何获取错误信息?

$('div#create_result').text(XMLHttpRequest.responseText); 

其中XMLHttpRequest内容

responseText: Content-Type: application/json; charset=utf-8 
{"error" : "User sdf doesn't exist"} 
status: 200 
statusText: parsererror 

我看到的结果是

Content-Type: application/json; charset=utf-8 {"error" : "User sdf doesn't exist"} 

,我也喜欢

User sdf doesn't exist 

我如何得到这个?

+3

如果您无论如何使用jQuery,为什么不使用它的[内置的Ajax库(HTTP://api.jquery。 com/category/ajax /)和[JSON速记方法](http://api.jquery.com/jQuery.getJSON/)? – 2011-05-06 12:14:44

+0

我不知道该如何开始。你能举一个与我的代码有关的例子吗? – 2011-05-06 12:23:15

+1

http://api.jquery.com/category/ajax/ – SLaks 2011-05-06 12:24:13

回答

-1

您可以使用正则表达式来提取值;例如:

var pattern = new RegExp(": \"(.+)\"}"); 
var str = 'Content-Type: application/json; charset=utf-8 {"error" : "User sdf doesn\'t exist"}'; 
var match = pattern.exec(str);  
alert(match[1]); 
3

请勿对此使用正则表达式。 jQuery的内置Ajax引擎带来了正确解析JSON所需的一切。

最原始的例子是这样的:

$.getJSON('your/url/here', function(data) 
    { $('#create_result').text(data.error);} 
); 

Documentation