How to get just the error message?
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]);
精彩评论