使用jsonp错误的jQuery ajax请求

bra*_*les 6 ajax jquery json jsonp

我正在编写一个应用程序,我需要从另一台服务器访问客户端的一些json数据.由于跨域问题,我计划使用jsonp.jQuery允许我使用$ .getJSON()方法执行此操作,但是,我无法判断方法是否已失败(即服务器没有响应或其他内容).所以我尝试使用$ .ajax来获取JSON数据.但它不起作用,我不知道该尝试什么.这是一个显示我的问题的示例:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
 <html>
 <head>
      <meta http-equiv="Content-type" content="text/html; charset=utf-8">
      <title>TEST</title>
      <script type="text/javascript" src="scripts/jquery-1.5.1.min.js"></script>
      <script type="text/javascript">
           $(document).ready(function() {
        $('#button_detect').click(function(){
            var feedApiAjax = 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=';
            var feedApiGetJSON = 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=';
            var feedUrl = 'http://www.engadget.com/rss.xml';

            $.ajax({
                url: feedApiAjax + feedUrl,
                datatype: 'jsonp',
                success: function(data) {
                    console.log('$.ajax() success');
                },
                error: function(xhr, testStatus, error) {
                    console.log('$.ajax() error');
                }
            });

            $.getJSON(
                feedApiGetJSON + feedUrl,
                function(data) {
                    console.log('$.getJSON success');
                });
        });
    });
      </script>
 </head>
 <body>
      <div id="button_detect">CLICK ME!!!!</div>
 </body>
Run Code Online (Sandbox Code Playgroud)

如果您使用此代码创建一个网页并单击"Click Me"div,您将看到$ .getJSON请求正在运行而$ .Ajax请求不正常.我已经尝试过/删除"callback =?" tg,使用了"jsonp"和"json"数据类型,但是没有这个工作.

关于我可能做错什么的任何想法?

干杯!

djp*_*jp3 7

当dataType是jsonp时,jquery不会自动触发错误函数.这在"错误"选项下的文档中进行了描述:

注意:不会为跨域脚本和JSONP请求调用此处理程序. 看到这里.

解决方法是明确指定超时作为选项.如果服务器在指定的时间内没有响应,则将调用错误函数.更多关于这里.


Ahm*_*med 5

之前我遇到过这个错误,并在使用jquery-JSONP后解决了

[例]

$.getJSON('http://server-url/Handler.ashx/?Callback=DocumentReadStatus',
  {
      userID: vuserID,
      documentID: vdocumentID
  },
  function(result) {
      if (result.readStatus == '1') {
          alert("ACCEPTED");
      }
      else if (result.readStatus == '0') {
          alert("NOT ACCEPTED");
      }
      else {
          alert(result.readStatus);
      }
  });
Run Code Online (Sandbox Code Playgroud)