使用 jsonp 响应实现 jQuery AJAX

Implementing jQuery AJAX with jsonp response

我在使用 jsonp 响应实施 jQuery AJAX 时遇到问题。我尝试访问它,但调用了失败的回调函数。我希望我的成功回调函数被调用。

另请注意,在普通 JavaScript 上我已经实现了它并且我知道 jsonp 和跨域 ajax fundas。它在我失败的 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 上查看此内容。

请帮忙!

您调用的 JSONP 格式具有 processJSONPResponse 的回调,因此您需要在 AJAX 请求的 jsonpCallback 参数中设置它:

$(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

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