试图通过jQuery.ajax()访问返回的JSONP数据

时间:2013-12-20 18:53:30

标签: jquery ajax json jsonp

我已经返回正确格式化的控制台中显示的JSONP数据。

group({
  "blah": "blah",
  "blahblah": "blahblah",
  "blahblahblah": "blahblahblah"
}); 

这是我的ajax电话。

$.ajax({
  type: 'GET',
  url: 'test.php',
  dataType: 'jsonp', 
  cache: false,
  jsonpCallback: 'group',
  statusCode: {
    404: function() {
      alert( "page not found" );
    }
  },
  success: function(group){
    console.log(group);
    $('#theTest').append(group.name);
  },
  error: function(response1, response2, response3){
    console.log("Fail!");
    console.log(response1);
    console.log(response2);
    console.log(response3);
  }
});

JSON包含' group'。当我尝试访问该数据时,我无法这样做。

  • group.name在控制台中有值,当我将其放在网站上时,它不会显示。
  • group [0]返回g
  • group [1]返回r
  • group [2]返回o

我很困惑为什么它会以这种方式返回。有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:1)

你的ajax请求不正确,应该是

$.ajax({
  type: 'GET',
  url: 'test.php',
  dataType: 'jsonp', 
  cache: false,
  jsonpCallback: 'group',
  statusCode: {
    404: function() {
      alert( "page not found" );
    }
  },
  success: function(group){
    console.log(group);
    $('#theTest').append(group.name);
  },
});

dataTypecachecallback不会作为数据字段传递,数据类型应为jsonp

答案 1 :(得分:0)

错误在您的服务器端响应中。 JSONP的工作方式是,指定一个已传递给GET请求的已知回调参数。在服务器端,您需要提取该参数以获取JSON填充的封装方法调用。

在您使用jsonpCallback:' group'的示例中,您的服务器端需要:

    $methodName = $_GET['group']
    $response = $methodName . '(' . <YOUR JSON RESPONSE> . ');'
    echo $response