【问题标题】:Accessing specific API访问特定 API
【发布时间】:2014-08-31 03:40:43
【问题描述】:

所以我正在尝试访问 OpenFEMA API 以获取资金数据,但我对 API 很陌生,我正在尝试使用 Javascript 访问 API。我遇到了同源问题并开始使用 CORS。

所以我的代码目前看起来像这样:

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();

    if ("withCredentials" in xhr) {
        // Check if the XMLHttpRequest object has a "withCredentials" property.
        // "withCredentials" only exists on XMLHTTPRequest2 objects.
            xhr.open(method, url, true);
        console.log('1');
    } else if (typeof XDomainRequest != "undefined") {
        // Otherwise, check if XDomainRequest.
        // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
        xhr = new XDomainRequest();
        xhr.open(method, url);
        console.log('2');
    } else {
        // Otherwise, CORS is not supported by the browser.
        xhr = null;
        console.log('3');
    }
    return xhr;
}

var xhr = createCORSRequest('GET', "http://www.fema.gov/api/open/v1/PublicAssistanceFundedProjectsDetails");

alert(xhr.responseText);

但警告框出现时是空的。我真的不确定我做错了什么。希望得到一些帮助。

【问题讨论】:

  • 对不起,我不知道这是什么意思
  • 你必须等待它被加载。
  • 哦,好吧,所以数据集目前太大了?

标签: javascript ajax cors


【解决方案1】:

您使用的函数只创建请求;它不发送它或等待结果。您仍然需要设置一个onReadyStateChange 处理程序,然后调用xhr.send() 来查看结果。

更重要的是,您访问的 API 不允许跨域请求。无法通过 Javascript 从站外访问。

【讨论】:

  • 感谢您实际检查 API。我开始觉得 API 不允许跨域请求。
  • 那么我该如何访问 API?
  • 你不能——至少,不是来自 Javascript。您需要从服务器端脚本或非基于 Web 的应用程序中调用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-09
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多