jQuery ajax链在CakePHP 3.8中选择下拉地址的国家,州,城市

时间:2020-04-03 08:23:32

标签: jquery ajax cakephp-3.x

我想选择链选择下拉列表以获取地址,而用户选择选项国家(印尼)然后显示选择选项国家雅加达,或用户选择国家马来西亚(马来西亚)然后显示选择沙巴州。

下面的MySQL表

Countries table
+--ID--+----Negara----+
|  1   |   Indonesia  |
|  2   |    Malaysia  |
+------+--------------+

States table
+--ID--+---countrie_id---+---Provinsi----+
|  1   |          1      |    Jakarta    |
|  2   |          1      |     Bali      |
|  3   |          2      |     Sabah     |
|  4   |          2      |    Serawak    |
+------+-----------------+----------------+

我想要的结果低于

select options countries

<select name="countrie">
  <option>Indonesia</options>
</select>

select options states

<select name="states">
   <option>Jakarta</option>
   <option>Bali</option>
</select>

控制国

public function index(){
  $negara = $this->Countries->find('all')->extract('Negara');
  $this->set(compact('negara'));
}

public function getCountries(){
  $negara = $this->Countries->find('all')->extract('Negara');

  return $this->response
    ->withType('application/json')
    ->withStringBody(json_encode([
      'jQueryNegara' => $negara,
      'result' => $result
    ]));
}

控制国

public function index(){
  $provinsi = $this->States->find('all')->extract('Provinsi');
  $this->set(compact('provinsi'));
}

public function getStates(){
  $provinsi = $this->Countries->find("all")->extract('Provinsi');

  return $this->response
    ->withType('application/json')
    ->withStringBody(json_encode([
      'jQueryProvinsi' => $provinsi,
      'result' => $result
    ]));
}

表单输入城市add.ctp

<?= $this->Form->control('countrie_id', [
  'type' => 'select',
  'id' => 'jQueryNegara',
  'options' => $negara 
]); ?>

<?= $this->Form->control('province_id', [
  'type' => 'select',
  'id' => 'jQueryProvinsi',
  'options' => $provinsi 
]); 
?>

城市内部的jQuery ajax add.ctp

$(function(){
  $('#negara').on('change', function() {
    var id = $(this).val();
    var targeturl = '<?= Router::url(["controller"=>"countries","action"=>"getCountries"]); ?>';
    if(id == '-1'){
      $('#provinsi').html(`<option value="-1">Select State</option>`);
    }else{
      $("#divLoading").addClass('show');
        $('#provinsi').html(`<option value="-1">Select State</option>`);    
          $.ajax({
              type:'post',
              url: targeturl,                  
              data:'id='+id+'&type=state',
              dataType: 'json',
              success:function(result){
                  $("#divLoading").removeClass('show');
                  $('#provinsi').append(result);
              }
          });   
      }
    });
});

我尝试重复并修复错误,但仍然无法正常工作。 谢谢想要帮助我的人

0 个答案:

没有答案