0

大家好,都想根据 cakephp 2.2 应用程序中的国家/地区选择为 Cities 生成动态下拉列表。我对 cakephp 很陌生。此外,我几乎找不到任何教程,因为它们大多是 1.3 或 1.2 版本。我在个人资料添加视图中有国家和城市的下拉菜单。这是我在国家控制器中的代码:

  public function citylist() {
         $this->layout=false;
         Configure::write('debug', 0);
         if($this->request->is('ajax')){    
        $country=$this->Country->read(null, $this->request['url']['country_id']);
        $code=$country['Country']['country_code'];
        $cities=$this->Country->City->find('list',array('conditions' =>array('City.country_code' => $code),'recursive' => -1,'fields' => array('id', 'name')));
        $this->set('cities',$cities);
}}

我的jQuery代码是这样的:

$(document).ready(function(){
$('#ProfileCountryId').live('change', function() {
if($(this).val().length != 0) {
  $.getJSON('/crush/countries/citylist',
              {country_id: $(this).val()},
              function(cities) {
                if(cities !== null) {
                  populateCityList(cities);
                }
    });
  }
});
});

      function populateCityList(cities) {
var options = '';

$.each(cities, function(index, city) {
options += '<option value="' + index + '">' + city + '</option>';
});
$('#ProfileHomeLocation').html(options);
$('#city-list').show();
}

我尝试进行更改,但它确实令人困惑,因为在差异示例中我看到了非常不同的方式。我不确定是否将该请求类型检查为 ajax,还是应该通过 request->data 或 params[url] 获取参数值。

我遵循了这两个现有的答案,这让我更加困惑。 cakephp 在 ajax 中传递下拉值 在 CakePHP 2.2 中连接被重置问题

这个错误很奇怪,第一次加载页面时它在控制台中显示错误“加载资源失败:服务器响应状态为 500(内部服务器错误)”。但是,如果我加载重新加载,然后在下拉列表中选择第一个值。它给出了错误

GET http://example.com/crush/countries/citylist?country_id=103 500(内部服务器错误) jQuery.ajaxTransport.sendjquery-1.7.2.js:8240 jQuery.extend.ajaxjquery-1.7.2.js:7719 jQuery.each.jQuery.(匿名函数)jquery-1.7.2.js:7245 jQuery.extend.getJSONjquery-1.7.2.js:7262(匿名函数)citylist.js:4 jQuery.event.dispatchjquery-1.7.2 .js:3332 jQuery.event.add.elemData.handle.eventHandle

不知道下一步该做什么。

4

1 回答 1

0

在像您这样涉及动态下拉框的情况下,我使用 ajax() jQuery 的方法来检索数据并替换元素的全部内容select。因此,您可以返回完整的 HTMLoption元素并将元素的内容替换select$('myselectelement').html(data). 这工作正常。

于 2012-08-17T13:19:30.947 回答