处理跨域jsonp调用的jQuery.ajax错误

mor*_*tic 14 ajax error-handling jquery jsonp cross-domain

我构建了一个ajax调用(jQuery 1.6.2)的测试用例,看起来像:

jQuery( document ).ready( function( $ ) {
    var test = function( x ) {
        $.ajax({
            url: 'http://www.someotherdomain.com/test.php',
            data: { x: x },
            dataType: 'jsonp',
            crossDomain: true,
            success: function( data ) { 
                console.log( data.name ); 
            },
            error: function() { 
                x++; 
                test( x ); 
            }
        });
    };
    test( 1 );
});
Run Code Online (Sandbox Code Playgroud)

相应的test.php文件如下所示:

if ( 5 > $_GET[ 'x' ] ) {
    header('HTTP/1.1 503 Service Temporarily Unavailable'); die();
} else {
    header( 'content-type: application/x-javascript' );
    echo $_GET[ 'callback' ] . '({"name":"Morgan"})';
}
Run Code Online (Sandbox Code Playgroud)

即使jQuery文档指出jsonp调用的错误处理程序永远不会被触发,这个脚本就像我想要的那样工作.它对test.php进行四次"不成功"调用,返回503错误,然后test()递归调用自己递增x直到aj​​ax调用"成功"并将数据输出到控制台.

所以上面的测试用例可行,但我的实际代码不起作用,看起来更像是以下内容:

jQuery( document ).ready( function( $ ) {
    var completed = 0;
    var fiftystates; // assume an array of state objects
    var updateState = function( index, state ) {
        var d = index % 5; // for subdomains sub0, sub1, sub2, sub3, sub4
        $.ajax({
            url: 'http://sub' + d + '.mydomain.com/update_state.php',
            data: { state: state.id },
            dataType: 'jsonp',
            crossDomain: true,
            success: function() { 
                completed++; 
                var complete_percent = completed / fiftystates.length * 100;
                $( '#progressbar' ).progressbar( 'value', completed_percent );
            },
            error: function() {
                updateState( index, state );
            }
        }); // end ajax
    }; // end updateState
    $( fiftystates ).each( updateState );
};
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这会循环遍历5个不同的子域,这些子域实际上只是同一个域的镜像,但由于update_state.php最多可能需要30秒才能完成,因此需要25分钟的时间将其缩短到不到3分钟.问题是服务器冲击导致一些ajax请求失败并出现503错误.在我的测试用例中,处理没问题,但在我的第二个例子中,似乎永远不会调用错误处理程序.

我无法弄清楚为什么测试用例会像我期望的那样工作,而第二个测试用例却没有.有任何想法吗?

小智 3

在您的测试用例中,您每次调用都会更改值 xf\xc3\xbcr...

\n\n

在其他代码中,您发送相同的索引值。这将返回相同的结果,而不是通过子域“循环”......

\n\n
    error: function() {\n        index++;\n        updateState( index, state );\n    }\n
Run Code Online (Sandbox Code Playgroud)\n