【问题标题】:dynamic drop down with cakephp and Jquery使用 cakephp 和 Jquery 动态下拉
【发布时间】:2012-08-17 13:09:19
【问题描述】:

大家好,都想根据 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 pass dropdown value in ajax The connection was reset issue in CakePHP 2.2.

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

获取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

不知道下一步该做什么。

【问题讨论】:

    标签: jquery dynamic drop-down-menu input cakephp-2.2


    【解决方案1】:

    在像您这样涉及动态下拉框的情况下,我使用 ajax() jQuery 的方法来检索数据并替换 select 元素的全部内容。因此,您可以返回完整的 HTML option 元素并将 select 元素的内容替换为 $('myselectelement').html(data),而不是通过 AJAX 调用返回 JSON 数据。这很好用。

    【讨论】:

    • 所以你的意思是我应该添加这个“'';”在控制器中的东西并设置一个最终的字符串而不是一个数组!如果您可以提供任何示例或提供任何链接,那就太好了,例如 cakephp 2.x 示例
    • 它不一定是 CakePHP 特定的。一些代码:$.ajax({ url: 'myurl', data: {...}}).done(function(data){ $('#mySelectElementId').html(data); }); 和 myurl 应该是来自 CakePHP 的控制器操作,它使用 echo $myHTMLOutput; 而不是 return $myHTMLOutput; 生成并返回 html 输出(实际上是一个字符串)
    • 其实问题出在参数值的传递上。我尝试对 2.2 版本的蛋糕使用更改后的方法,并且效果很好。虽然我接受了你的回答,因为它给了我想法,传递单个字符串,因此我能够发现 Jquery 函数工作正常。
    猜你喜欢
    • 2018-06-03
    • 2020-09-25
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    相关资源
    最近更新 更多