【问题标题】:Why Unable to get success callback in Jquery/ajax call to RESTful services?为什么无法在 Jquery/ajax 调用 RESTful 服务时获得成功回调?
【发布时间】:2016-02-16 04:38:38
【问题描述】:
function GET() {
        jQuery.support.cors = true;
        $.ajax({
            url: 'http://localhost:32253/api/UserDetail/GetRoleDetails',
            type: 'GET',
            async:true,
            contentType: "application/json",
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            error: function (xhr, status)
            {
                alert(status);
            },
            success: function (data) {
                alert("Success!");
            }

        });
        return false;
    }

我对 ajax 非常陌生,我尝试对我的服务方法进行 ajax 调用,该方法返回值。但是成功回调函数从未被触发。我只得到错误。可能是什么原因? 我尝试使用 dataType 到 jsonp 和其他类似的解决方案,这些解决方案在 Stackoverflow 中找到了关于这个问题。没有解决。我得到的服务器响应为 200 ok。

【问题讨论】:

  • 尝试使用complete 而不是success
  • 请求的负载是什么?其余服务是否需要一些参数?你为什么不发布你的休息服务的代码。
  • 这可能是内容来源策略的问题,在 Content-Security-Policy 中添加您的域并尝试。
  • 我可以在 IE 中获得 Success 回调,但在 Chrome 中失败。

标签: javascript jquery asp.net ajax rest


【解决方案1】:

试试这个代码

$.ajax({
        type: "POST",
        url: URL,
        async: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        jsonp: "onJSONPLoad",
        jsonpCallback: "newarticlescallback",
        crossDomain: "false",
        beforeSend: function (xhr) {
        },
        error: function (request, status, error) {
            console.log("Error In Web Service...." + request.responseText);
            return false;
        },
        success: ajax_success,
        complete: function (xhr, status) {
        }
    });

在你的页面中创建函数“ajax_success” 如下所示

function ajax_success(parsedJSON) { //you code here 
}

【讨论】:

    【解决方案2】:

    这可能对你有帮助 试试这个代码

     $.ajax({
            type: "POST",
            url: URL,
            async: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            jsonp: "onJSONPLoad",
            jsonpCallback: "newarticlescallback",
            crossDomain: "false",
            beforeSend: function (xhr) {
            },
            error: function (request, status, error) {
                console.log("Error In Web Service...." + request.responseText);
                return false;
            },
            success: function (data) {
                Result = data;
            },
            complete: function (xhr, status) {
            }
        });
    

    【讨论】:

    • 我在 IE 中尝试过,我能够得到响应,但在 chrome 的情况下失败了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 2011-11-28
    • 1970-01-01
    相关资源
    最近更新 更多