这个while循环的正确JSON结构是什么?

时间:2011-11-09 11:33:36

标签: ajax json jquery

我对JSON有点新鲜,所以试着了解这是最好的方法。我有两个变量:postcode和energyrating我想放入JSON然后解析为for循环。

我可以使用一个变量,但是当我有两个变量时它不起作用。

这是我的JSON:

header('Content-type: application/json');

$postcodeArray = array('postcodes' => array("E6 2JG","SE1 2AQ","DA1 1DZ"), 'energyrating' => array("A","B","C","D","E","F","G"));

die(json_encode($postcodeArray));

这是我的jQuery:

function addNew(postcodes) {
if(postcodes.length > 0) {
    for(var i = 0; i < postcodes.length; i++) {

        var address = postcodes[i];
        var rating = energyrating[i];

        geocoder.geocode( { 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);  

                var image = '../img/markers/' + rating + '.png';
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    icon: image
                });
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }
} else {
    alert("Sorry, no data was found.");
}
}

如何使用这两个变量?

2 个答案:

答案 0 :(得分:0)

什么不能正常工作?

阅读您的代码,我会说您的代码中存在错误。您的addNew函数中缺少energyrating参数:

function addNew(postcodes, energyrating) {

假设您按照以下方式调用您的函数:

addNew(jsonData.postcodes, jsonData.energyrating);

答案 1 :(得分:0)

使用json变量来存储数据:

$postcodeArray = '{"postcodes":{"0":E6, "1":"2JG", "3":"SE1 2AQ","4":"DA1 1DZ"}, "energyrating":{"0":"A","1":"B","2":"C","3":"D","4":"E","5":"F","6":"G"}}';

取代

$postcodeArray = JSON.parse('postcodes' => array("E6 2JG","SE1 2AQ","DA1 1DZ"), 'energyrating' => array("A","B","C","D","E","F","G"));

您可以访问这些值。

或者在第一行的json_decode(postcodes)函数中尝试addNew