如何获取错误消息?

时间:2011-05-06 12:12:38

标签: javascript jquery ajax

我有这段代码

$('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

我怎么做到这一点?

2 个答案:

答案 0 :(得分:3)

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

最原始的例子如下:

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

Documentation

答案 1 :(得分:-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]);
相关问题