I'm receiving some error response in ajax error function;
$.ajax(Request).error(function (Response) {
var content = JSON.stringify(Response.responseText);
var obj = JSON.parse(content);
console.log("Response.responseText:",Response.responseText);
console.log("Response.responseText.Message:", Response.responseText.Message);
console.log("Response.responseText[Message]:", Response.responseText["Message"]);
console.log("content:", content);
console.log("content.Message:", content.Message);
console.log("content[Message]:", content["Message"]);
console.log("obj:", obj);
console.log("obj.message:", obj.Message);
console.log("obj[Message]:", obj["Message"]);
});
Here are outputs of console.log :
I need to access Message but none of them create access to its value. How can I access Message?
Main Question
- why all of them are undefined?
- How can I access Message?
Solution
var parsed= JSON.parse(startpaymentResponse.responseText);
console.log("parsed:", parsed);
console.log("parsed.Message:", parsed.Message);
console.log("parsed[Message]:", parsed["Message"]);
Meanwhile when I copy Response.responseText to JSON Deserialize Online, everything is fine.
Response.responseText: {"Message":"The request is invalid.","ModelState":{"model.Amount":["The field Amount must be a string or array type with a minimum length of '4'."],"model.TotalAmount":["The field TotalAmount must be a string or array type with a minimum length of '4'."]}}
CodePudding user response:
Okay, so the problem is that Response.responseText
is already a string. You don't need to do JSON.stringify(Response.responseText)
. Please directly, parse it to JSON and then use the object:
$.ajax(Request).error(function (Response) {
var obj = JSON.parse(Response.responseText);
console.log("obj.Message", obj.Message);
});
CodePudding user response:
please give us more information about your code!