【问题标题】:REST/XMLHttpRequest with JavaScript带有 JavaScript 的 REST/XMLHttpRequest
【发布时间】:2014-11-02 03:10:59
【问题描述】:

您能帮我解决问题并通过 REST API 获取数据吗:

Info: GET User // 此端点返回有关特定用户的信息。 HTTP 请求 - https://www.codewars.com/api/v1/users/:id_or_username

有效页面:https://www.codewars.com/api/v1/users/Luqpa

我正在使用以下脚本:

function createRequest() {
          var result = null;

            result = new XMLHttpRequest();

          return result;
    }


    var req = createRequest(); // defined above
        // Create the callback:
        req.onreadystatechange = function() {
          if (req.readyState != 4) return; // Not there yet
          if (req.status != 200) {
            // Handle request failure here...
            return;
          }
          // Request successful, read the response
          var resp = req.responseText;
          // ... and use it as needed by your app.
    }

    url = "https://www.codewars.com/api/v1/users/Luqpa";

    req.open("GET", url, true);
    req.send();

    var status = req.status;
    var status_text = req.statusText;

    var xmlDocument = req.responseXML;
    console.log(xmlDocument);
    console.log(status);
    console.log(status_text);

    console.log (req);

所有响应都是 null 或 0

我尝试了各种可能性并阅读了其他教程,但没有找到解决方案。请建议我如何解决它并从页面获取信息....

提前致谢。

【问题讨论】:

    标签: javascript rest xmlhttprequest


    【解决方案1】:

    您的代码在我看来不错。我认为您正面临跨源资源共享问题。

    您在浏览器中添加以下标志后是否对其进行了测试?

    --disable-web-security --allow-file-access-from-files --allow-file-access
    

    这些标志将允许您的程序跨域访问资源。

    请记住,这些标志仅用于开发目的,不适用于生产环境。

    【讨论】:

      【解决方案2】:

      您的 req.responseXML 为空,但 req.responseText 不是。 你有一个 JSON 格式的答案。 尝试将 responseXML 更改为 responseText,看看是否对您有帮助。

      【讨论】:

        猜你喜欢
        • 2015-11-04
        • 1970-01-01
        • 2017-08-23
        • 1970-01-01
        • 2016-01-03
        • 2013-01-21
        • 2018-07-19
        • 2021-09-27
        • 1970-01-01
        相关资源
        最近更新 更多