【问题标题】:Cross Domain Ajax fail - parseerror as callback not called跨域 Ajax 失败 - 未调用 parseerror 作为回调
【发布时间】:2017-03-31 18:03:52
【问题描述】:

我设置了一个需要跨域的ajax,一些API工作没有任何错误,但有些返回parserror
我不知道为什么会发生这种情况以及如何解决它,希望有人能给我一些指导,谢谢。

这是我的代码:

// After OAuth2 to get the token
$.ajaxSetup({
    dataType: 'jsonp',
    statusCode: {
        401: function() {
            window.open('page for oauth2');
        }
    }
});

$.ajax({
    url: 'https://redbooth.com/api/3/me',         // this one work without problem
    method: 'GET'
})
.done(function( data, textStatus, jqXHR ) {
    alert('success');
});

$.ajax({
    url: 'https://redbooth.com/api/3/projects?order=id&archived=false',
    method: 'GET'
})
.done(function( data, textStatus, jqXHR ) {
    alert('test');
})
.fail(function( jqXHR, textStatus, errorThrown ) {
    // this API will throw error
    // jqXHR: status = 200, readyState = 4, statusText = "load"
    // textStatus: parserror
    // errorThrown: xxx was not called
    var test = 1;
});

我已经从他们的控制台和 fiddler 中检查了返回值:

[{"type":"Project","created_at":0,"updated_at":0,"id":0,"permalink":"test-1cc1c3","organization_id":0,"archived" :false,"name":"test","description":null,"start_date":null,"end_date":null,"tracks_time":false,"public":true,"publish_pages":false,"settings" :{},"user_id":0,"deleted":false,"last_goal_user_id":0}]

请注意我这里修改了值,把那些id替换成0就行了

我尝试在 JSON 验证器 中验证返回值或使用$.parseJSON('return value'),两者都可以毫无问题地返回 JSON 对象。

我尝试了以下方法:
- I am getting a json parse error on a cross-domain ajax call not sure how to get rid of the issue
- 设置'jsonp': false
- 设置'dataType': 'text',导致跨域问题
- 设置'dataType':'text,'crossDomain':true,仍然是跨域问题

【问题讨论】:

    标签: jquery ajax cross-domain jsonp


    【解决方案1】:

    如果 jsonp 不起作用,您可以尝试从服务器调用 url,而不是从 javascript/ajax 尝试。

    $.ajax({
        url : 'proxy.php',
        data: {url :'https://redbooth.com/api/3/projects?order=id&archived=false'},
        method: 'GET'
    })
    .done(function( data, textStatus, jqXHR ) {
        alert('test');
    })
    

    proxy.php

    <?php
    if(isset($_POST['url']) and !empty($_POST['url'])) {
    $data = file_get_contents($_POST['url']);
    print $data;
    }
    ?>
    

    【讨论】:

    • 如果可能的话,我会尽量避免
    • 避免服务器干预是个好习惯,但对于跨域问题,我建议您使用服务器端触发。希望这对您有所帮助。
    猜你喜欢
    • 2012-04-14
    • 2013-11-26
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 2011-02-03
    • 2010-10-13
    相关资源
    最近更新 更多