REST/XMLHttpRequest with JavaScript

REST/XMLHttpRequest with JavaScript

本文关键字:JavaScript with XMLHttpRequest REST      更新时间:2023-09-26

您能帮我解决问题并通过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);

所有响应要么为空,要么为0

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

提前谢谢。

您的代码对我来说很好。我认为您正面临跨来源资源共享问题。

在将以下标志附加到浏览器后,您是否对其进行了测试?

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

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

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

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