2016-09-06 148 views
-2

我需要創建動態下拉選項。第二次選擇取決於第一次輸入。 我想從cakephp應用程序的ajax請求到控制器中的操作,但我用ajax代碼stucked。在php中的Ajax請求

我嘗試:

<?= $this->Form->select('country_id' ,$optionsCountry, ['id' => 'country_id'], 'onclick' => 'getcit'); ?> 

<?= $this->Form->select('Cities', $optionsCities); ?> 

比我想創建功能至極將在選擇選項的變化叫,但我stucked。

<script> 
function getcities(str){ 
    var xhttp; 
    xhttp = new XMLHttpRequest(); 
    xhttp.onreadystatechange = function(){ 
     xhttp.open('POST', 'controller' => 'cities', 'action' => 'getcit',+str , true); 
     xhttp.send(); 
    } 
} 

我不知道如何調用函數在HTML中,的onchange? ONSELECT? 如何從第一個輸入獲取數據,將其發送給控制器動作,從控制器獲取數據並將其設置爲另一個選擇?

謝謝 最好的問候,

我發現jquery.ajax作爲也許simplier解決方案,但我又stucked:

<script> 
$(document).ready(function){ 
    $('#country_id').change(function() { 
     $.ajax({ 
      url: "", 
      data: "", 
      type: 'POST' 
     }); 
    }); 
} 
; 

你能幫我: 熒光燈,如何從第一個選擇 獲取數據 - 將其轉發給控制器 - 並將返回的值設置爲secon select

謝謝

+0

[這裏](https://developer.mozilla.org/en-US/docs/Web/Events)是一個事件列表。 'someElement.onXXX'會在正確的時間調用它。至於問題的其餘部分,請添加更多關於您嘗試的細節,以便人們瞭解您的問題。 – Actorclavilis

回答

1

您必須先創建改變<select>後Ajax調用,這對於第二<select>返回數據。

function getcities(id) { 
    $.ajax({ 
     method: 'POST', 
     url: 'some.php', 
     data: { 
      country_id: id 
     }, 
     success: function (data, status) { 
      $('.second_select').html(data); // If returns as html 
     } 
    }); 
    return; 
}