How to get all json values in an ajax success?
I have an example json result:
{"Products": [{"ProductIndex": "1", "ProductCode": "116001", "ProductPrice": "$517.00"},{"ProductIndex": "2", "ProductCode": "37732", "ProductPrice": "$288.00"}],"Totals": [{"CartTotal": "$805.00", "Quantity": "2", "DiscountTotal": "0", "LastProduct": "0"}]}
I have this jQuery:
jQuery(function(){
jQuery.ajax({
url: '/AjaxCart.asp',
cache: false,
dataType: 'text',
success: function(data) {
var json = eval('(' + data + ')');
var quantity;
var cartTotal;
var screenId;
quantity = json.Totals[0].Quantity;
cartTotal = json.Totals[0].CartTotal;
screenId = json.Products[0].ProductCode;
$("#content_area").prepend(screenId);
},
error: function() {
return false;
}
});
});
It works, but screenid is only pulling the first value of ProductCode. I need it to loop through the entire result and display both ProductCod开发者_开发问答e values. I've tried putting the .each function around different things but with no results. Any help?
I think I am close with this but it's still not working:
pIndex = json.Products[0];
for(var i = pIndex.length; i--;) {
screenItem = pIndex[i];
$("#content_area.").prepend(screenItem.ProductCode)
I think you just need to change pIndex = json.Products[0];
to pIndex = json.Products;
, at the moment you're trying to loop through a single object, the first element of the Products
array.
pIndex = json.Products;
for(var i = 0; i < pIndex.length; i++) {
screenItem = pIndex[i];
var $span = $('<span />').text(screenItem.ProductCode);
$("#content_area.").append($span);
}
If you are always returning json from your ajax call, it would be best to set your ajax dataType property to "json" so that you don't need to parse the text by yourself (with either the eval method or the parseJSON method). Also, the jQuery.each function is preferable to a standard javascript for loop.
I would write your code like this:
jQuery(function(){
jQuery.ajax({
url: '/AjaxCart.asp',
cache: false,
dataType: 'json',
success: function(data) {
jQuery.each(data.Products, function(index, element) {
$("#content_area").prepend(element.ProductCode);
});
},
error: function() {
return false;
}
});
});
精彩评论