1

我有一个包含 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) {

     ...

任何帮助深表感谢

4

1 回答 1

1

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

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

$.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) {

        ...
    }
});
于 2012-05-12T07:05:31.853 回答