hawkfalcon
hawkfalcon

Reputation: 652

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?

Upvotes: 2

Views: 7462

Answers (2)

ThinkingStiff
ThinkingStiff

Reputation: 65341

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();

Upvotes: 3

Fahd A.
Fahd A.

Reputation: 134

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

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

Upvotes: 2

Related Questions