【问题标题】:Calling REST Api with JSONP & JQuery使用 JSONP 和 JQuery 调用 REST Api
【发布时间】:2012-11-01 22:23:13
【问题描述】:

我在 MVC4 中创建了 REST API,当我编写来自提琴手的请求时它工作正常。但在我的应用程序中,我需要通过 jsonp 调用,因为它会跨域请求。但是当我调用这个服务时,它给了我如下所示的错误:

Jquery JsonP 调用 ..

$.ajax({
        type: "POST" ,
        url: "http://127.0.0.1:81/api/sites/GetDomainAvailability?apikey=asfasfdsf&callback=?",
        data: { SubDomain: subDomain, ParentDomain: parentDomain, ResellerId: resellerId },
        cache: false,
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            if (callback)
                callback(response.d);
        },
        error: function (response) {
            if (callback)
                error(response.d);
        },
    });

错误:

【问题讨论】:

标签: c# asp.net-mvc jsonp


【解决方案1】:

现在你没有做 JSONP。它仍然是 POST 请求。要使其成为 JSONP,您只需将 dataType: "jsonp" 添加到您的 $.ajax() 调用中。您还可以删除一些其他冗余参数,如内容类型和“回调”参数(但这是可选的)。因此,您的代码应如下所示:

$.ajax({
    url: "http://127.0.0.1:81/api/sites/GetDomainAvailability?apikey=asfasfdsf",
    data: { SubDomain: subDomain, ParentDomain: parentDomain, ResellerId: resellerId },
    datatype: "jsonp",
    cache: false,
    success: function (response) { /* ... */ },
    error: function (response) { /* ... */ },
});

也要做好准备,您的请求将被转换为 GET 请求,并且看起来像 /GetDomainAvailability?apikey=key&callback=jquery123&SubDomain=sss&ParentDomain=ppp&ResellerId=123&_=4398572349857

因此,为此准备您的服务器端代码。

【讨论】:

    猜你喜欢
    • 2014-12-23
    • 2011-05-12
    • 2014-12-14
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多