JSON使用AJAX获取表单值

时间:2011-05-08 07:09:47

标签: javascript jquery json

我不知道我是否累了,或者为什么我无法做到正确请帮助我需要的是

    <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'));
            } else {
                $('#country').append($('<option>').text(value).attr('value', value));
            };
        });
        }
    });
};
</script>

外部文件中的代码类似于

<?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);
?>

我得到的回应是

["AG,ANTIGUA AND BARBUDA","AU,AUSTRALIA","BR,BRAZIL","CA,CANADA","KY,CAYMAN ISLANDS","CN,CHINA"]

我需要的是填写标签的选项我也得到了这个部分,但我不能让它填写国家代码AG作为值和名称像

<option value="AG">Antigua</option>

请为我分解我真的很困惑,累了几个小时的头痛。

2 个答案:

答案 0 :(得分:1)

您需要拆分值

$.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])));
            };
        });

答案 1 :(得分:0)

如果您不必分割字符串,它会使您的ajax回调更容易..

while( $result2 = mysql_fetch_array($results2) ) {
    $json[] = array('short'=>$result2['short'],
                    'full' => $result2['full']
              );

}

然后你可以通过

解析
$.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'])));
            };
        });