简体   繁体   English

如何从外部URL获取JSON数据

[英]How get JSON data from external URL

I would like to be able to read information from a small page. 我希望能够从一小页中读取信息。

I have the address of a JSON service that displays the following information: 我有一个显示以下信息的JSON服务的地址:

在此处输入图片说明

And I wish I could keep the number that appears. 我希望我能保留显示的数字。

I tested this example and work correctly, however when I try with my URL nothing happens. 我测试了此示例并正常工作,但是当尝试使用URL时,没有任何反应。 I do not know if I am to understand the problem correctly, but I wish someone could please help me. 我不知道我是否能正确理解问题,但我希望有人可以帮助我。

If have any questions, I try to explain as best as possible. 如有任何疑问,我会尽力解释。

I ask now apologize for the inconvenience. 造成不便之处,敬请原谅。

The code that I used 我使用的代码

var getJSON = function(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        resolve(xhr.response);
      } else {
        reject(status);
      }
    };
    xhr.send();
  });
};

getJSON('http://MYADDRESS/json.do?_ULN[1]').then(function(data) {
    alert('Your Json result is:  ' + data.result); //you can comment this, i used it to debug

    result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
  alert('Something went wrong.');
});

You can't for security reasons. 您不能出于安全原因。 See the same origin policy for JavaScript. 请参见JavaScript的相同来源策略

There are some workarounds that exploit browser bugs or corner cases, but using them is not recommended. 有一些变通办法可以利用浏览器的错误或极端情况,但是不建议使用它们。

The best approach is having a server-side proxy that receives Ajax requests, and in turn, sends HTTP requests to other servers. 最好的方法是让服务器端代理接收Ajax请求,然后将HTTP请求发送到其他服务器。 This should be carefully implemented by sanitizing input and whitelisting the types of requests that are sent, and the servers that are contacted. 应该通过清理输入并将发送的请求类型和联系的服务器列入白名单来仔细实现此目的。

Your problem exist because of the browser Same-origin policy. 由于浏览器的同源策略,您的问题存在。

One solution to your problem is to use the method JSON-P or CORS. 解决您的问题的一种方法是使用JSON-P或CORS方法。 The method is well explained here : http://json-p.org/ and here : http://www.sitepoint.com/jsonp-examples/ . 该方法在http://json-p.org/http://www.sitepoint.com/jsonp-examples/中有很好的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM