Reputation: 21
I have the following code, the first part of which gets JSON from PHP after a drop down selection is triggered. The result is placed in a div called "results" just to verify that it works. Everything looks good up to that point. I also have a couple lines of code which parse the JSON, and display the individual elements in a sequence of alerts, again, just to verify that it functions up to this point, which it does. However, after this, I try to parse the JSON in a similar manner as in creating the alerts, only place the individual results in separate arrays. I have a check to alert the results as the $.each is executed, so that I can see if the code block is functioning. However, it does not work. I am guessing that perhaps my brackets are not setup properly, or perhaps I need to declare another function somewhere. Can anyone suggest what might be the problem?
Thanks for your help.
$(document).ready(function() {
$('#routesDropDown').change(function() {
var queryParam = 'routesStations=' +$(this).val();
$.post('getstations.php', queryParam, processResponse);
});
function processResponse(data) {
$('#results').html(data);
// parse the data and store in variable, "obj"
var obj = jQuery.parseJSON( data );
// iterate through each value in the "obj" variable
$.each(obj, function(key, value) {
alert(value.color + ' ' + value.abbr + ' ' + value.lat + ' ' + value.lng);
});
//THIS IS THE PART THAT DOES NOT WORK...
var obj = jQuery.parseJSON( data ) {
var color = [];
var abbr = [];
var lat = [];
var lng = [];
$.each(obj, function(value) {
color.push(value.color);
abbr.push(value.abbr);
lat.push(value.lat);
lng.push(value.lng);
alert(value.color + ' ' + value.abbr + ' ' + value.lat + ' ' + value.lng);
})};
});
Upvotes: 2
Views: 780
Reputation: 1
$.post('getstations.php', queryParam, processResponse,"json");
queryParam你现在是一个字符串不是一个object对象 jquery api文档说明这里是需要传入一个{xxx:xxx}对象
Upvotes: 0
Reputation: 40639
I think your json is not created you can check it in console, if the code is not returning a json then you should pass a json
parameter in the $.post
function like
$.post('getstations.php', queryParam, processResponse,"json");
See the documentation here: jQueryPost
Upvotes: 0
Reputation: 1869
I think that callback function accepts two values index and value
So the code should be
$.each(obj, function(index, value) {<--- Here i have added index. Like your above code.
color.push(value.color);
abbr.push(value.abbr);
lat.push(value.lat);
lng.push(value.lng);
alert(value.color + ' ' + value.abbr + ' ' + value.lat + ' ' + value.lng);
})
Upvotes: 1
Reputation: 71
For me, the secret to jquery is the selectors...
I'd do a quick "alert(data)" before your $.each() function, just to be sure you're getting what you think you're getting...
Upvotes: 1