简体   繁体   中英

Parse json from an external site with JavaScript

I am trying to parse some json on an external site but I am having trouble. It must be with JavaScript or JQuery, as it is for a chrome extension. To get to the point: I need to get the number from an external URL with the json {"_visitor_alertsUnread":"0"} and set the number returned to a variable. How do I go about doing this?

I have tried several things such as JSON.parse but it isn't working:(

In short: How do I get the number from this json, which is on an external site, and set it to a variable?

You cannot get data from an external URL (in a different domain) in Javascript unless the site supports JSONP or Cross-Origin Resource Sharing. If it does, then use XMLHttpRequest to get the data and JSON.parse() to read it.

Script:

var xhr = new XMLHttpRequest();
xhr.open( 'GET', 'example.com/json', true );

xhr.onload = function () {
    var unread = window.JSON.parse( xhr.responseText )._visitor_alertsUnread;
};

xhr.onerror = function () {
    //process error
};

xhr.send();

Try this with http://api.jquery.com/jQuery.getJSON/

$.getJSON('your_url', function (jsonobj) {
    var unread;
    unread = jsonobj._visitor_alertsUnread;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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