首页 文章

jQuery $ .ajax使用JSONP调用跨域,返回状态200,但调用错误函数而不是成功

提问于
浏览
2

我的Web应用程序正在尝试从属于不同域的另一台服务器访问该信息 . 由于它是一个跨域的ajax调用,我使用“dataType”作为“JSONP”而不是JSON .

现在在WebInspector-> Network选项卡中,我看到请求成功并且填充了响应 . 但是从不调用success()函数 . 它总是调用status = 200的错误函数 .

由于它是一个JSONP请求,jQuery追加“callback =?”到URL的末尾,即使在获得有效响应之后也从未调用回调方法 . 不确定出了什么问题?

$(document).ready(function() {
    // When you click the Get Instances button:
    $('#getInstances').click(function(){
        $.ajax({
            type: "GET",
            url: "http://178.28.167.221:8080/us-east-1/instance/list.json",
            contentType: "application/json; charset=utf-8",
            accept: "application/json",
            crossDomain: "true",
            headers: {'Access-Control-Allow-Origin','*'},
            dataType: "jsonp",
            success: function(msg) {
                result = JSON.stringify(msg);
                var obj = $.parseJSON(result);
                console.log(obj);
                $('#instancesTable').append('<tr><td>' + obj.autoScalingGroupName + '</td><td>' + obj.amiId + '</td><td>' + obj.instanceId + '</td><td>' + obj.instanceType +'</td></tr>');                                     
            },
            error: function(xhr, ajaxOptions, thrownError, textStatus, responseText) {
                console.log(name + ' environment failed with error: ' + xhr.status + "  " + thrownError);

                var errorMessage = "Error";
                if (xhr.status == 0) {
                    errorMessage = "Can't Connect";
                }
            }
        });
    });
});

我还通过在我的ajax请求中包含以下内容进行了验证:

jsonp: 'callback',
        jsonpCallback: 'jsonpCallback'

并定义回调函数如下:

function jsonpCallback(data){
         alert("jsonpCallback");
       }

即使请求成功并且可以从服务器获得响应(在WebInspector的“网络”选项卡中显示),也从未调用过jsonCallback .

服务器的响应是一个JSON对象数组 . [ ..]

注意:我尝试将contentType更改为“application / javascript”,因为响应是一个JSON对象数组 . 但没有任何作用:(

1 回答

  • 0

    我有类似的问题,并解决了它 . 您尚未指定您的服务 . 就我而言,它是一个WCF服务 .

    我不得不加上这个 .

    <webHttpBinding>
            <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
          </webHttpBinding>
    

    并在服务中将绑定配置设置为上述配置

    即: bindingConfiguration="webHttpBindingWithJsonP"

    这解决了这个问题 . 它们可能是在PHP或其他平台上实现相同的类似方法

相关问题