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?
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?
Share Improve this question edited Apr 4, 2013 at 19:53 ThinkingStiff 65.4k30 gold badges147 silver badges241 bronze badges asked Jul 7, 2012 at 2:27 hawkfalconhawkfalcon 6521 gold badge12 silver badges24 bronze badges 7- Your question is very vague. You should try to pin it down to something more specific (preferrably with some code examples). – hugomg Commented Jul 7, 2012 at 2:31
- Okay, sorry, I'm just trying to figure out how to get the number from a json page on a external site. – hawkfalcon Commented Jul 7, 2012 at 2:35
- 2 1. Get the data using ajax (helpful: api.jquery./jQuery.ajax). 2. Parse JSON. (simple js object value dereferencing). Try implementing this and if it doesn't work update your question with the specific error and the code you tried. Good luck! :) – nbrooks Commented Jul 7, 2012 at 2:40
- Edited question, hopefully it's clearer now. – hawkfalcon Commented Jul 7, 2012 at 2:41
-
1
Could you tell us how it is not working? What happens when you use
JSON.parse()
? Does it throw an error? If so, can you post what that is? – redhotvengeance Commented Jul 7, 2012 at 5:06
2 Answers
Reset to default 3You 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./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./jQuery.getJSON/
$.getJSON('your_url', function (jsonobj) {
var unread;
unread = jsonobj._visitor_alertsUnread;
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744670487a4587010.html
评论列表(0条)