2014-01-19 67 views
2

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”的值。这怎么能实现?

+4

没有必要再分析它,使用' response.a'和'response.b'来访问a和b的值 –

+0

'response'看起来不是一个字符串。做一个'typeof response',你会发现它已经是一个自动从json响应中创建的对象。 – SoonDead

+0

比它不是一个字符串。你可以像@PranavRam所说的那样直接访问它的属性。或者,您可以像这样使用索引运算符:'response [“a”]'和'response [“b”]'。 – SoonDead

回答

2

它已经在JSON格式。你不需要再解析它。

像这样使用它。

response.a; 
    response.b; 
1

检查:

var ajaxResult = '{"a":"apple","b": true}'; 

var json= $.parseJSON(ajaxResult); 

console.log(json.a); 
2

请仔细阅读它,我也做了一些改变:)如果有任何疑问,请向我

$("#day").datepicker({ 
     onSelect: function(request) { 
      $.ajax({ 
       type: "POST", 
       url: '${pageContext. request. contextPath}/url.htm', 
       data: JSON.stringify({ 
        id: '${someId}' 
       }), 
       dataType: 'json', 
       success: function (response) { 
        if(response['b'] === true) { 
         $("#fruit").val(response['a']); 
        } 
       } 
      }).fail(function(xhr, status, error){ 
       console.log('error:' + status + ':' + error + ':' + xhr.responseText); 
      }); 
     } 
     }); 
+0

使用JSON数据类型,尝试了两种形式:'console.log(response ['d']);''和console.log(response.d);';仍然未定义 –