I'm pretty new to using JSON (and to jQuery's Ajax features in general). What I'm trying to do is set up a separate file containing a JSON object, point to that file, store the object as a variable, and access the object's properties using dot notation.
jQuery.parseJSON() sort of allows me to do what I want, but I want to take the next step of 开发者_开发百科pointing to a separate file.
For example, the following behaves exactly as I would expect, opening an alert box that says 'red':
var test = $.parseJSON('{"simple":"red"}');
alert(test.simple);
The following, which points to a file containing the same JSON object, doesn't work, opening an alert box that says 'undefined':
var test = $.getJSON('simple.json');
alert(test.simple);
I'm obviously not using this correctly. What's the correct way to do what I'm trying to achieve here?
Checkout the getJSON docs: http://api.jquery.com/jQuery.getJSON/
you should be doing something like:
$.getJSON('simple.json', function(data) {
alert(data.simple);
});
always pays to read the API docs
I think you've misunderstood getJSON. It doesn't return a JSON object, but is shorthand for parsing a response text from an AJAX request as JSON.
When you call getJSON, you're actually performing an asynchronous request. When you call alert, the request hasn't come back yet.
Try:
var test;
$.getJSON('simple.json', {}, function(data) {
test = data;
alert(test.simple);
});
Shabba: http://api.jquery.com/jQuery.getJSON/
$.getJSON
issues a HTTP GET request to the server and executes a callback when the data is received.
$.getJSON('simple.json', function(data) {
alert(data.simple);
});
Alternatively, if you are using jQuery 1.5 or later, you can use the new jqXHR syntax.
$.getJSON('simple.json')
.success(function(data) {
alert(data.simple);
});
Difference between getJson and parseJson
jQuery.getJSON() is used to load JSON-encoded data from the server using a GET HTTP request.
$.getJSON( "ajax/test.json", function( data ) {
$.each( data, function( key, val ) {
//your actions
});
jQuery.parseJSON() takes a well-formed JSON string and returns the resulting JavaScript value.
var obj = jQuery.parseJSON( '{ "name": "John" }' );
In other words
The $.getJSON() method loads the JSON-encoded data from the server using a GET HTTP request based on a URL to which the request is sent. You may then choose to use $.parseJSON() method to parse the JavaScript object or array as defined by the JSON structure.
getJSON is for loading data, not parsing
Load JSON-encoded data from the server using a GET HTTP request.
$.get('path/to/file',
function(data) {
my_variable = data;
},
"json"
);
精彩评论