Cannot access json file with javascript

2019-08-03 17:17发布

问题:

I want to read the json content of this page : http://89.92.40.250:8010/dreamteam/interface/get_event_detail.php?id=397 with javascript.

So i began this script :

var req = new XMLHttpRequest();
    req.open("GET", "http://89.92.40.250:8010/dreamteam/interface/get_event_detail.php?id=397", true); 
    req.onreadystatechange = monCode;   
    req.send(null);      

    function monCode() { 
        if (req.readyState == 4) { 
            var doc = eval('(' + req.responseText + ')');
            alert(req.responseText);
        }
    } 

when I want to show the content I use alert(req.responseText); and I don't see the content. Plus I have a syntax error with Firebug : syntax error : var doc = eval('(' + req.responseText + ')');

Impossible with JSONP.

Can we extract the content of the page, then convert it to JSON format then parse it ??

回答1:

If you can't create a your own proxy, you should use YQL to avoid cross domain problem.

here is an example url for id=397,

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D'http%3A%2F%2F89.92.40.250%3A8010%2Fdreamteam%2Finterface%2Fget_event_detail.php%3Fid%3D397'&format=json&diagnostics=true

and you can set id dynamically like this,

var id = 397;
var baseurl = "http://query.yahooapis.com/v1/public/yql?q=";
var q = "select * from json where url = 'http://89.92.40.250:8010/dreamteam/interface/get_event_detail.php?id="+id+"'";  
var url = baseurl + encodeURI(q) + "&format=json&diagnostics=true";
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.onreadystatechange = monCode;
req.send(null);

function monCode() {
    if (req.readyState == 4) {
        var data = JSON.parse(req.responseText).query.results;
        console.log(data);
        //console.log(data.event);
        alert(data.event.title);
    }
}​

And here is a jsFiddle DEMO

Usage Limits for YQL

  • Per application limit (identified by your Access Key): 100,000 calls per day
  • Per IP limits: /v1/public/: 2,000 calls per hour; /v1/yql/: 20,000 calls per hour


回答2:

This is not possible due to cross-domain restrictions; your page should be hosted on the same host.

You could invest in the following alternatives:

  • use JSONP (probably won't work in your case)
  • use server-side script on the same host that will pull the file contents (like a proxy)
  • look at ways to configure cross domain acces control: https://developer.mozilla.org/En/HTTP_access_control (not likely an option for you either)


回答3:

Since you are making a request from 127.0.0.1 to 89.92.40.250:8010 it is going to be a cross domain request, it is a cross domain request even if you access a different port on the same machine like 127.0.0.1:8080.

If you have control over the content rendered by 89.92.40.250:8010 you could use jsonp to get around the cross domain restriction but it needs some changes on the backend or you can use a functionality provided by http://jsonp.jit.su/ which basically contacts the server on your behalf, creates a jsonp response which you can handle.



回答4:

As I said above in my comment, you cannot do cross-domain AJAX requests. Browsers normally forbid this.

If you really want to do a cross-domain request, there are several options, one being proxying (configure your local webserver to send the request to the remote server) and the other JSONP).

JSONP basically consists in adding an extra script tag to your HTML document whilst using the request URL as src. This allows you to bypass cross-domain security control, as you can always include JS resources from other sites. However, the remote server must know that it has to apply a prefix to the request (i.e. read_data({ /* JSON response */});, otherwise the returned information won't be processed.

UPDATE

jQuery, for instance, can handle JSONP transparently, as if it were a normal AJAX request:

http://api.jquery.com/jQuery.ajax/

i.e.:

$.ajax({url:'http://your/request/url/',
        jsonp: 'your_desired_prefix',
        success: function(result) {
          /* result should hold you JSON data */
        });