在jquery中解析json对象的数组

时间:2012-05-12 06:55:56

标签: jquery-mobile

我有一个包含3个json对象的数组:它看起来像这样:

PHP代码:

echo json_encode(array(
   'BigArea' => $BigArea_Obj,
   'Categories' => $Categories_Obj,
   'Sub_Categories' => $Sub_Categories_Obj
));

Real Json包含主要的3个实体(BigArea,Categories,Sub_Categories)

{
"BigArea":

[{"area_id":"1","area_name":"Beirut","country_id":"1"},{"area_id":"2","area_name":"North Maten","country_id":"1"}],

"Categories":

[{"categ_id":"2","categ_name":"Actvities","categ_pic":"1-1024.jpg","categ_big_area_id":"1","big_area_id":"1"},{"categ_id":"6","categ_name":"Hotels","categ_pic":"2-1024.jpg","categ_big_area_id":"1","big_area_id":"1"},{"categ_id":"5","categ_name":"Restaurants","categ_pic":"002_1024.jpg","categ_big_area_id":"1","big_area_id":"1"}],

"Sub_Categories":

[{"categ_id":"2","product_id":"5","product_name":"dr pepsi","product_pic_thumb":"","prod_categ_id":"2","small_area_id":"1"},{"categ_id":"5","product_id":"6","product_name":"Sushi","product_pic_thumb":"","prod_categ_id":"5","small_area_id":"1"}]

}

我需要的是循环遍历每个对象,所以我使用了下面但它对我来说没有正常工作:

$.ajax({
type: "POST",
url: "server/bigarea_categ_subcateg.php",
dataType: "json",
data: CountryId,
success: function (b) {
BigArea_Categ_Sub_Object = b;
$.mobile.changePage("#BigAreaPage", { changeHash: false });
}
});

var BigArea_Object = BigArea_Categ_Sub_Object.BigArea;
var Categories_Object = BigArea_Categ_Sub_Object.Categories;
var SubCategories_Object = BigArea_Categ_Sub_Object.Sub_Categories;

$.each(BigArea_Object, function (index, value) {

 ...

  $.each(Categories_Object, function (index, value) {

   ...

    $.each(SubCategories_Object, function (index, value) {

     ...

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

AJAX代表异步(非阻塞)请求。这意味着在调用$.ajax之后立即没有BigArea_Categ_Sub_Object。

您应该将所有以var BigArea_Object = BigArea_Categ_Sub_Object.BigArea;开头的代码移动到success函数体(一旦服务器响应可用就调用)。 E.g。

$.ajax({
    type: "POST",
    url: "server/bigarea_categ_subcateg.php",
    dataType: "json",
    data: CountryId,
    success: function (b) {
        BigArea_Categ_Sub_Object = b;
        $.mobile.changePage("#BigAreaPage", { changeHash: false });
        var BigArea_Object = BigArea_Categ_Sub_Object.BigArea;
        var Categories_Object = BigArea_Categ_Sub_Object.Categories;
        var SubCategories_Object = BigArea_Categ_Sub_Object.Sub_Categories;

        $.each(BigArea_Object, function (index, value) {

        ...

        $.each(Categories_Object, function (index, value) {

        ...

        $.each(SubCategories_Object, function (index, value) {

        ...
    }
});