Problem retrieving values from JSON object
I am having a little t开发者_运维问答rouble retrieving the values from a JSON object that is returned after a jQuery GET request and I am hoping someone here will be able to help. I think I may be doing something stupid but cannot figure it out.
In firebug the response is show as:
[{"plan_id":"2","plan_name":"plan 2","plan_desc":"plan 2 desc"}]
However when I try to retrieve the values they are undefined.
Here is the code I am using:
jQuery(function(){
jQuery("#add_plan").click(function(){
var val = jQuery("#plan_id").val();
if (!isNaN(val))
{
jQuery.ajax({
success: function(data) {
if (data)
{
jQuery("#plan-list").append(
"<li>"
+ " <label for=\"plans\">" + data.plan_name + "</label>"
+ "</li>"
);
}
},
type: 'GET',
dataType: 'json',
url: 'http://example.com/plans.php?plan=' + val
});
}
});
});
Any help would be appreciated.
Thanks
Paul
Since it's an array, you need data[0].plan_name
instead, or possibly a loop like this if you expect multiple results:
$.each(data, function() {
$("<label for='plans' />").text(this.plan_name).wrap("<li />").parent()
.appendTo("#plan-list");
});
You can give it a try here.
Looking closely, your JSON result
[{...}]
is an object ({}
) inside an array ([]
).
You will be able to access the values using
data[0].plan_name
The above posters are correct, but don't assume there will always be an Array, test the value of data every time. If it's an object, proceed. If it's an object/array loop.
精彩评论