当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Fill array with json response

问题描述:

I'm trying to populate array in my validation code with distinct values from one column, and logic was that on focus on certain element I would send ajax request and populate array with JSON response. But I'm still a novice in JQuery and it seems I cant get it right, so if anyone can help.

$('input#search').on("focus", function(){

$.ajax({

type:"get",

dataType: "json",

url:"ajax_php/get_distinct_cities.php",

success:function(data){

$.each( data.city, function( i, itemData ) {

cities[i] = itemData;

});

}

});

});

PHP:

<?php

mysql_connect("localhost","root","");

mysql_select_db("pickante");

$sql = "SELECT DISTINCT city FROM uc_items";

$result = mysql_query($sql);

$cities = array();

while($row = mysql_fetch_assoc($result))

{

$cities[] = $row;

}

echo json_encode($cities);

?>

JSON Print:

[{"city":"Belgrade"},{"city":"Novi Sad"}]

网友答案:

Just loop the array and push

for (var i = 0; i < data.length; i++) {
    cities.push(data[i].city);
}
网友答案:

As timeJV said just loop the array and add the cities to you array, here is an example of how it will be using the $.each, but the previous answer will do the work.

 $.each(data, function( i, itemData ) {
                     cities.push(itemData.city);
          });
分享给朋友:
您可能感兴趣的文章:
随机阅读: