开发者

Help required making use of an array returned from a jquery ajax request

I have a simple jquery ajax call which posts a car manufacturer and responds with an array of car models so that a select menu (options) of models can be populated.

I am building the array in php/mysql as follows.

$make = $_POST['make'];
//QUERY
$query=mysql_query("SELECT id,model FROM cars WHERE manufacturer='$make'")or die(mysql_error());
while($row=mysql_fetch_array($query)){

    $id=$row['id'];
    $model=$row['model'];

    $arr[$id]=$model;
}   
//ADD TO CALLBACK
$data['models'] = $arr;
$data['success'] = true;
//RETURN JSON
echo json_encode($data);

The Jquery ajax response is set to JSON as a data type and in the success function i have placed the following to test the response where data.models is the data returned from the php.

$.each(data开发者_StackOverflow.models,function(key, value) { 
alert(key + ': ' + value); 
});

I can see from firebug that the data is being returned but the ajax always throws an error response.

I dont understand why.

A typical response i am getting is

{"models":{37:"DB7 Vantage Coupe '00",38:"DB9 Coupe '03",39:"DB9 Coupe '06",40:"V8 Vantage '99",41:"Vanquish '04"},"success":true}

Maybe there is some clues in the above outout format. I am not comfortable enough with arrays to know if the response is right or wrong.

Any ideas would be more than helpful.


This is not proper JSON:

{"models":{37:"DB7 Vantage Coupe '00",38:"DB9 Coupe '03",39:"DB9 Coupe '06",40:"V8 Vantage '99",41:"Vanquish '04"},"success":true}

In JSON all keys are strings, but you have integers (such as 37 and 38) as keys. Try converting the $id to string in the php code before putting them in $arr, so they become quoted in the JSON (though I'm not sure why json_encode isn't doing that automatically)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜