Retrieve the message of an play.mvc.results.Error during a Ajax using the responseText
let's say i make a Play! ajax post using this jquery code, i need to show the error in a alert box.
$.ajax({
type: "post",
url: "@{removeQuoteToWatch()}",
dataType : "json",
data: {
'symbol' : symbol
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
},
success: function(data){
...
}
});
the output in the alert box is the following :
{
type: 'play.mvc.results.Error',
message: 'Can't find symbol : Watch list is empty'
}
How can i only retrieve the message part?
i tryed something like
error: function(xhr, a开发者_高级运维jaxOptions, thrownError){
alert(xhr.responseText.message);
},
but it's not working
thanks,
As you can read here
http://api.jquery.com/jQuery.ajax/#jqXHR
the responseText is a string; if you want to parse it as json you could do
var res = $.parseJSON( xhr.responseText );
alert(res.message);
I personally do prefer not to throw a 500 error for logical issues, but use a normal 200 and provide the return-status and user-error in json.
the answer above is basically right BUT looking at it closer (and actually reproducing it) it appear that you have found a bug in the play framework. The framework should return
{ "type":"play.mvc.results.Error", "message":"Watchlistempty" }
while it does return:
{ type: 'play.mvc.results.Error', message: 'Watch list empty' }
which is not valid json.
I checked the play! lighthouse project and it does not seem to be reported before. I created a ticket at:
http://play.lighthouseapp.com/projects/57987-play-framework/tickets/1073-templateserror500json-returns-invalid-json#ticket-1073-2
精彩评论