Ajax调用如何读取JSON字符串[jQuery的]
$("#day").datepicker({
onSelect: function(request) {
$.ajax({
type: "POST",
url: '${pageContext. request. contextPath}/url.htm',
data: JSON.stringify({
id: '${someId}'
}),
dataType: 'json',
contentType: "application/json;charset=utf-8",
success: function (response) {
if(response.b === true) {
$("#fruit").val(response.a);
}
}
}).fail(function(xhr, status, error){
console.log('error:' + status + ':' + error + ':' + xhr.responseText);
});
}
});
从ajax
呼叫字符串响应如下
{
"a": "apple",
"b": true
}
我曾尝试使用var json = $.parseJSON(response);
读它,我得到异常Uncaught SyntaxError: Unexpected token o
console.log(response);
显示控制台上的数据为
Object {
"a": "apple",
"b": true
}
我想获取“a”和“b”的值。这怎么能实现?
没有必要再分析它,使用' response.a'和'response.b'来访问a和b的值 –
'response'看起来不是一个字符串。做一个'typeof response',你会发现它已经是一个自动从json响应中创建的对象。 – SoonDead
比它不是一个字符串。你可以像@PranavRam所说的那样直接访问它的属性。或者,您可以像这样使用索引运算符:'response [“a”]'和'response [“b”]'。 – SoonDead