【问题标题】:How to consume Web API without server side code, using only Ajax如何在没有服务器端代码的情况下使用 Web API,只使用 Ajax
【发布时间】:2026-02-08 08:45:01
【问题描述】:

我在我的主机文件中添加了以下两个主机条目:

127.0.0.1 na_api.com

127.0.0.1 na_upload.com

127.0.0.1 na_api.com 用于从数据库中检索一些数据并返回 JSON,而127.0.0.1 na_upload.com 是使用 API 的网站。

目前,我有以下 Ajax 调用,用于调用 API 并获取一些数据。这是 Ajax 调用:

this.ajaxRetrieve = function (url, data, onSuccessCallback) {
    $.ajax({
        url: url,
        data: data,
        type: 'GET',
        crossDomain: true,
        onsuccess: function (result) {
            onSuccessCallback(result);
        }
    });
}

上面输出如下错误:

请求的资源上没有“Access-Control-Allow-Origin”标头

如果不需要像 .Net 之类的后端服务器端代码,我该如何解决这个问题?

【问题讨论】:

标签: jquery asp.net .net ajax


【解决方案1】:

我终于在this 文章中找到了适合我的东西。

我将以下内容添加到我的 Web API 的 Web.config 文件的 <syetm.webServer> 部分

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

这是我用来发出请求的 Ajax 调用:

$.ajax({
        url: url,
        data: data,
        type: 'GET',
        async: false,
        success: function(result) {
            onSuccessCallback(result);
        },
        error: function(xhr, status, error) {
            onErrorCallback(xhr, status, error);
        }
    });

【讨论】:

    【解决方案2】:

    使用 JSONP

    $.ajax({
                                    url: url,
                                    type: 'GET',
                                    crossDomain: true,
                                    contentType: "text/json",
                                    dataType: "jsonp",
                                    success: function (data) { // },
                                    error: function (xhr, status, error) { }
                              });
    

    【讨论】:

      最近更新 更多