JSON get form values using AJAX
I dont know if i am tired or why i cannot get it right please help what i need is
<script language="javascript">
$(document).ready(function(){
getResultsCountry();
})
function getResultsCountry() {
$.ajax({
url:'suggest_country.html',
type:'POST',
data: 'q=',
dataType: 'json',
success: function( json ) {
$('#country')[0].options.length = 0;
$.each(json, function(i, value) {
if (value=='<?php echo $country; ?>') {
$('#country').append($('<option>').text(value).attr('value', value).attr('selected', 'selected')开发者_StackOverflow社区);
} else {
$('#country').append($('<option>').text(value).attr('value', value));
};
});
}
});
};
</script>
Code in external file looks like
<?php
$results = mysql_query('SELECT DISTINCT country FROM MyTable WHERE country LIKE \'%\' ORDER BY country');
while( $result = mysql_fetch_array($results) ) {
$cities = $cities.' short = \''.$result['country'].'\' OR';
}
$cities = substr($cities, 1,strlen($cities)-3);
$results2 = mysql_query('SELECT full, short FROM `Countries` WHERE '.$cities);
$json = array();
while( $result2 = mysql_fetch_array($results2) ) {
$json[] = $result2['short'].','.$result2['full'];
}
echo json_encode( $json );
mysql_close($db2);
?>
Response i am getting is
["AG,ANTIGUA AND BARBUDA","AU,AUSTRALIA","BR,BRAZIL","CA,CANADA","KY,CAYMAN ISLANDS","CN,CHINA"]
What i need is to fill it in the options for tag i got this part too, but i cannot make it fill country code AG as value and name as name like
<option value="AG">Antigua</option>
please break it down for me i am really confused and tired its been hours of headache.
You need to split values
$.each(json, function(i, value) {
var arr_values = value.split(',');
if (value=='<?php echo $country; ?>') {
$('#country').append($('<option>').text(arr_values[1]).attr('value', arr_values[0]).attr('selected', 'selected'));
} else {
$('#country').append($('<option>').text(arr_values[1]).attr('value', arr_values[0])));
};
});
It would make your ajax callback much easier if you didn't have to split your strings..
while( $result2 = mysql_fetch_array($results2) ) {
$json[] = array('short'=>$result2['short'],
'full' => $result2['full']
);
}
And then you can parse by
$.each(json, function(i, value) {
if (value['full']=='<?php echo $country; ?>') {
$('#country').append($('<option>').text(value['full']).attr('value', value['short']).attr('selected', 'selected'));
} else {
$('#country').append($('<option>').text(value['short']).attr('value', value['full'])));
};
});
精彩评论