我试图使用jQuery从我的JSON对象中检索错误message
。我该怎么做呢?谢谢!
我的JSON看起来像这样:
{
"error":{
"errors":[
{
"domain":"global",
"reason":"invalidParameter",
"message":"Invalid value 'asdfcom.com'. Values must match the following regular expression: 'http(s)?://.*'",
"locationType":"parameter",
"location":"url"
}
],
"code":400,
"message":"Invalid value 'asdfcom.com'. Values must match the following regular expression: 'http(s)?://.*'"
}
}
我的Javascript看起来像这样:
error: function(xhr, status, error) {
$("#mobileResults").css("color", "red");
$("#mobileResults").text(xhr.responseText);
console.log(xhr.responseText)
$('.fa-spinner').hide();
}
答案 0 :(得分:3)
很简单:
var jsonObj = JSON.parse(xhr.responseText); //your object;
var message = jsonObj.error.errors[0].message; // Values must match the following regular expression:
var outsideMes = jsonObj.error.message; // Values must match the following regular expression:
您可以尝试使用此代码段,它可以正常运行
var obj = {
"error": {
"errors": [{
"domain": "global",
"reason": "invalidParameter",
"message": "Invalid value 'asdfcom.com'. Values must match the following regular expression: 'http(s)?://.*'",
"locationType": "parameter",
"location": "url"
}],
"code": 400,
"message": "Invalid value 'asdfcom.com'. Values must match the following regular expression: 'http(s)?://.*'"
}
}
console.log(obj.error.errors[0].message);
console.log(obj.error.message);

答案 1 :(得分:0)
尝试使用jQuery.parseJSON
方法。
var jsonObj = jQuery.parseJSON(xhr.responseText);
console.log(jsonObj.message);