doujiao6507 2015-09-14 05:30
浏览 85
已采纳

如何使用ajax json处理php键值对

I have a php script that returns timezones from the form country SELECT and populates the timezone SELECT.

'US' produces ...

PHP

Timezones Array
(
 [0] => America/Adak
 [1] => America/Anchorage
 [2] => America/Boise
 [3] => America/Chicago
...etc...
 [28] => Pacific/Honolulu
)

echo json_encode($timezones_array_above);

But I dont know how to handle the key/value data in javascript/jquery, so I had to create another loop in the php script to name the pair to use the javascript below.

PHP

// I WANT TO GET RID OF THIS EXTRA LOOP AND MOVE IT TO JAVASCRIPT PART BELOW!
foreach ($timezones as $key => $value) {
  $json[] = array(
    'id' => $value,
    'name' => $value
  );
}

echo json_encode($json);

HTML / JQUERY

$('#country').on('change', function (){
  $.post('{$constant->get('AJAXPAGE')}/timezonesbycountry.php', {country: $(this).val()}, function(data){

/*
// I WANT TO HANDLE THE RAW TIMEZONE ARRAY HERE!
// AND REPLACE THIS WITH KEY & VALUE VARS...
    var options = '';
    for (var x = 0; x < data.length; x++) {
      options += '<option value="' + data[x]['id'] + '">' + data[x]['name'] + '</option>';
    }
*/
    $('#timezone').html(options);
  }, 'json');
});

How do I do this in javascript?


Here is the replacement I came up with, which works, but is this correct?

$('#country').on('change', function (){
    $.post( "{$constant->get('AJAXPAGE')}/timezonesbycountry.php", {country: $(this).val()})
    .done(function( data ) {
    var result = JSON.parse(data);
    var options = '';
        $.each(result, function(k, v) {
            options += '<option value="' + v + '">' + v + '</option>';
        });
    $('#timezone').html(options);
    });
});
  • 写回答

2条回答 默认 最新

  • doudou890510 2015-09-14 19:45
    关注

    Here is what I came up with, stripped, leaving the basics..

    PHP (timezonesbycountry.php)

    if (empty($_POST['country'])) {
        $timezones = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
    }else{
        $timezones = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $_POST['country']);
    }
    
    header('Content-Type: application/json');
    echo json_encode($timezones);
    

    JQUERY

    $('#country').on('change', function (){
        $.post( 'timezonesbycountry.php', {country: $(this).val()})
        .done(function( data ) {
        var options = '';
            $.each(data, function(k, v) {
                options += '<option value="' + v + '">' + v + '</option>';
            });
        $('#timezone').html(options);
        });
    });
    

    HTML

    <select class="form-control" id="country" name="country" required>
        <option value="">Select One</option>
        <option value="AF">Afghanistan</option>
        <option value="US">United States</option>
        ...etc...
    </select>
    
    <select class="form-control" id="timezone" name="timezone" required>
        <option value="">Select One</option>
        ...etc...
    </select>
    

    I use temp keys for all ajax requests, and sanitize the data in the php though...

    $.post( '{$constant->get('AJAXPAGE')}/timezonesbycountry.php', {act: 'SOMETHING', ajaxkey: 'KEYHERE', country: $(this).val()})
    

    I also pre-populate the country/timezone selects with php array's; you could pre-populate the timezones with the ajax instead though if your country select is static.

    Thanks for the help, hopefully this help somebody else.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝