2017-10-08 55 views
1

我遇到问题实施jQuery AJAX与jsonp响应。我尝试访问它,但我的失败回调函数被调用。我想让我的成功回调函数被调用。用jsonp响应实现jQuery AJAX

另请注意,在普通JavaScript中,我已经实现了它,并且我知道jsonp和跨域ajax基金会。它在我失败的jQuery上。

的JSONP位置 - here

的代码是:

   $.ajax({ 
       url: "http://www.demo.yogihosting.com/jquery/jsonp/data1.json", 
       dataType: "jsonp", 
       type: "POST", 
       contentType: "application/json; charset=utf-8", 
       success: function (result, status, xhr) { 
        alert(result); 
       }, 
       error: function (xhr, status, error) { 
        alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText) 
       } 
      }); 

您可以在jQuery AJAX with jsonp on CodePen查看此。

请帮忙!

+0

你可以发布失败的回调错误消息吗? – 2017-10-08 19:27:33

+0

@SamDev我试图从本地获取jsonp响应,并且出现此错误 - 'jQuery31006235097177340809_1507490891841未被称为200负载' – yogihosting

+0

尝试使用dataType:“json” – 2017-10-08 19:31:59

回答

1

你打电话的JSONP格式有processJSONPResponse回调,所以你需要设置的参数jsonpCallback您的AJAX请求:

$(document).ready(function() { 
    $("#jsonpButton1").click(function(e) { 
    $.ajax({ 
     url: "http://www.demo.yogihosting.com/jquery/jsonp/data1.json", 
     dataType: "jsonp", 
     type: "POST", 
     jsonpCallback: 'processJSONPResponse', // add this property 
     contentType: "application/json; charset=utf-8", 
     success: function(result, status, xhr) { 
     console.log(result); 
     }, 
     error: function(xhr, status, error) { 
     console.log("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText) 
     } 
    }); 
    }); 
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<button id="jsonpButton1">Button 1</button> 

Working example

注意,我必须将工作示例放在小提琴中,因为SO不允许出现不安全的出站请求。

+0

非常感谢你,它完美的工作 - jsonpCallback:'processJSONPResponse'是我的代码中缺少的东西。 – yogihosting