开发者

How to get just the error message?

开发者 https://www.devze.com 2023-03-03 02:59 出处:网络
I have this code $(\'div#create_result\').text(XMLHttpRequest.responseText); where the content o开发者_Go百科f XMLHttpRequest is

I have this code

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

where the content o开发者_Go百科f XMLHttpRequest is

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

The result I see is

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

where I would have liked

User sdf doesn't exist

How do I get just that?


Don't use a regular expression for this. jQuery's built-in Ajax engine brings along everything that is needed to parse the JSON properly.

The most primitive example looks like this:

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

Documentation


you can use a regular expresion to extract value; something like:

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]);
0

精彩评论

暂无评论...
验证码 换一张
取 消