Javascript 获取 XMLHttpRequest 的 JSON 结果

标签 javascript

我正在尝试获取 Jenkins 服务器的某些 XMLHttpRequest 的结果

var oReq = new XMLHttpRequest();
var res = oReq.open("get", "http://" + IP + ":8080/job/Job1/lastBuild/api/json?depth=1", true);
oReq.send();

但是我没有收到 var res 的输入,这是为什么?

编辑

我尝试了此处评论的答案之一,我得到了

No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是什么意思?

谢谢

最佳答案

最好使用jQuery的$.getJSON、$.ajax、$.get等

但如果您想要 native 方式(不想加载外部库或更喜欢 native JavaScript 等),请尝试以下操作:

// returns proper XMLHttpRequest object
    function getXmlHttp(){
      var xmlhttp;
      try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
          xmlhttp = false;
        }
      }
      if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
        xmlhttp = new XMLHttpRequest();
      }
      return xmlhttp;
    }

    // creates CORS Request object
    function createCORSRequest(method, url) {
      var xhr = getXmlHttp();
      if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
      } else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
      } else {
        xhr = null;
      }
      return xhr;
    }
    
    // does request and calls callback function and passes json data to callback function
    function getJson(url, callback) {
      var request = createCORSRequest('GET', url);
      if(!request) {
        console.log('Cannot create request');
        return false;
      }

      request.onload = function() {
        var data = JSON.parse(request.responseText);
        callback(data);
      };

      request.onerror = function() {
        console.log('Error happen');
      };

      request.send(null);
    }
    
    // usage
    //var url = "http://" + IP + ":8080/job/Job1/lastBuild/api/json?depth=1";
    var url = 'http://time.jsontest.com/?alloworigin=true';
    getJson(url, function(data) {
      alert(data.time);
      console.log(data);
    });


关于CORS:http://www.html5rocks.com/en/tutorials/cors/

另外:在具有您请求的 IP 的 Web 服务器中必须定义有关 CORS 的访问规则。
在这里阅读:http://enable-cors.org/server_nginx.html , http://enable-cors.org/server_apache.html



您还可以在服务器端应用程序中添加自定义 header 。
例如在 PHP 中:

header('Access-Control-Allow-Origin: *');

在 RoR 中:https://gist.github.com/dhoelzgen/cd7126b8652229d32eb4

关于Javascript 获取 XMLHttpRequest 的 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31563875/

相关文章:

javascript - 缩放 div 以适合窗口但保持纵横比

javascript - 在 WordPress 前端添加选择

javascript - 展开一个子菜单其他人应该自动隐藏在 jquery 中

javascript - 在 php 中将 Javascript DateTime 格式化为日期 (‘ymdHis’ )

javascript - 当一个 div 被移除时,按钮停留在最后一个 div

javascript - 使用 fabric.js 将 Canvas 形状绘制为椭圆形 lauout

javascript - 无法解析react-viro中的模块

JavaScript、Eval 和 New——穷人的工厂

javascript - 同步2个div之间的滚动

c# - 如何序列化表单字段并将其发送到服务器,jquery?