如何创建jquery对象数组

时间:2014-01-06 19:22:13

标签: javascript jquery arrays

我的项目中有城市对象。我想用一些城市对象创建一个jquery数组。我可以从.ashx文件中获取城市列表并创建单个城市对象。但我无法将它们推向阵列。这是我的代码:

 var postDataCity = { funcName: "GetCities" };

        var cities = [];
        var city = {};

        $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "json",
            url: "KurumInformation.ashx",
            data: postDataCity,
            async: true,
            success: function (msg) {
                $.each(msg, function (i, v) {
                    city.M_CityId = this.M_CityId ;
                    city.M_CityName= this.M_CityName;
                    cities.push(city);
                });
            },
            error: function (d) {
                alert('error :' + d);
            },
        });

        console.log(cities);

在此之后我检查城市,但我认为有一个错误,因为我无法在控制台中看到城市。我的错误在哪里?

3 个答案:

答案 0 :(得分:2)

您的代码几乎没问题,您必须在循环内声明city

此外,您只需在推送后移动console.log即可查看结果:

success: function (msg) {
    $.each(msg, function (i, v) {
        var city = {};   //Move declaration here
        city.M_CityId = this.M_CityId ;
        city.M_CityName= this.M_CityName;
        cities.push(city);
    });
    console.log(cities);   //Move it here
},

如果你在外面宣布它,你每次都会在数组中添加相同的城市参考。

此外,由于ajax调用是异步的,因此在ajax调用完成之前执行旧console.log,这就是您看到空结果的原因。

干杯

答案 1 :(得分:0)

$.each(msg, function (i, v) {
       city.M_CityId = v.M_CityId ;
       city.M_CityName= v.M_CityName;
       cities.push(city);
});

它会正常工作。

答案 2 :(得分:-1)

在进行AJAX调用回调之前显示变量。你应该在回调中有你的console.log()。