使用 JQUERY、AJAX 和 PHP 填充选择框 [英] Populating a select box using JQUERY, AJAX and PHP

查看:25
本文介绍了使用 JQUERY、AJAX 和 PHP 填充选择框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前发布了一个问题,但运气不佳,我希望清除第二个下拉列表的内容并重新填充下拉列表,具体取决于第一个下拉列表中的值.

I posted a question earlier and didn't have much luck, I am hoping to clear the contents of a second dropdown and repopulate the dropdown, depending on the value that is in the first dropdown.

我有以下选择框,如下所示:

I have the following select boxes as seen below:

   <select name = "car" id="Cars" onchange="myFunction(this)">
            <option value="0">Toyota</option>
            <option value="1">Audi</option>
            <option value="2">Suzuki</option>
   </select>

在这个下拉菜单下面,我还有另一个模型下拉菜单:

Underneath this dropdown I also have another drop down for models:

    <select id="emptyDropdown">
            <option value="0">R8</option>
            <option value="1">Quattro</option>
            <option value="2">A6 hatchback</option>
    </select>

onchange 我想清除第二个下拉列表并用与汽车品牌相关的模型填充它.EG.

onchange I want to clear the second dropdown and populate it with models related to the car brand. EG.

Audi - A8, A6, A4 etc.
Suzuki - Swift, Panda etc.


<script>
  function myFunction(obj)
  {
    $('#emptyDropdown').empty()
    var dropDown = document.getElementById("carId");
    var carId = dropDown.options[dropDown.selectedIndex].value;
    $.ajax({
            type: "POST",
            url: "/project/main/getcars",
            data: { 'carId': carId  },
            success: function(msg){
                ?????????
            }
        });
  }
</script>

然后我有以下 PHP 函数,如下所示(我使用的是 codeigniter) - 该函数使用 Car ID 并返回所有模型的列表,如下所示:

I then have the following PHP function as seen below(I am using codeigniter) - this function uses the Car ID and returns a list of all the models as seen below:

public function getCars(){
        $this->load->model('car_model');

        $this->form_validation->set_rules('carId', 'carId', 'trim|xss_clean');

        if($this->form_validation->run()){
            $carId = $this->input->post('carId');
            $carModels = $this->user_management_model->getCarModels($carId);
        } else {
            echo "error";
        }   
}

然后我不知道如何返回 PHP 生成的数组中的每个元素,重新填充 ID = "emptyDropdown" 的下拉列表.PHP 生成的数组具有以下结构:

I then do not know how to return each element in the array produced in PHP, to repopulate the dropdown list with ID = "emptyDropdown".The array generated in PHP has the following structure:

Array ( [0] => Array ( [ModelName] => R8 V6 Twin Turbo [ModelID] => 19 ) [1] => Array ( [ModelName] => A6 Hatchback  [ModelID] => 107 ) )

澄清这个问题 - 我将如何获取数组中的每个元素并将其作为下拉列表中的一个新选项?有没有办法将数组返回到javscript,然后在ajax调用的success方法中重新填充?

To clarify the question - how would I take each element in the array and put this as a new option in the dropdown list? is there a way to return the array to javscript and then repopulate in the success method of the ajax call?

非常感谢任何帮助,非常感谢

Any help would be much appreciated, many thanks in advance

推荐答案

此答案提供了对代码的必要修改.

This answer provides the necessary modifications to your code.

免责声明:如果没有看到确切的安装,请注意可能有多种因素导致这在您的安装中无法按原样"运行.我不知道您的路由是如何设置的,或者您是否使用 Firebug 或其他控制台来观看 ajax 调用,但这应该为您提供构建块:

DISCLAIMER: Without seeing the exact install, be aware there may be a variety of factors that cause this to not work "as-is" in your installation. I do not know how your routes are set up, or if you are using Firebug or some other console to watch the ajax calls, but this should give you the building blocks:

首先,将您的 php 更改为 输出 数组作为 json 编码的字符串:

First, change your php to output the array as a json-encoded string:

public function getCars(){
        $this->load->model('car_model');

        $this->form_validation->set_rules('carId', 'carId', 'trim|xss_clean');

        if($this->form_validation->run()){
            $carId = $this->input->post('carId');
            $carModels = $this->user_management_model->getCarModels($carId);
            // Add below to output the json for your javascript to pick up.
            echo json_encode($carModels);
            // a die here helps ensure a clean ajax call
            die();
        } else {
            echo "error";
        }   
}

然后,修改您的脚本 ajax 调用以具有获取数据并将其添加到下拉列表的成功回调:

Then, modify your script ajax call to have a success callback that gets the data and adds it to your dropdown:

function myFunction(obj)
  {
    $('#emptyDropdown').empty()
    var dropDown = document.getElementById("carId");
    var carId = dropDown.options[dropDown.selectedIndex].value;
    $.ajax({
            type: "POST",
            url: "/project/main/getcars",
            data: { 'carId': carId  },
            success: function(data){
                // Parse the returned json data
                var opts = $.parseJSON(data);
                // Use jQuery's each to iterate over the opts value
                $.each(opts, function(i, d) {
                    // You will need to alter the below to get the right values from your json object.  Guessing that d.id / d.modelName are columns in your carModels data
                    $('#emptyDropdown').append('<option value="' + d.ModelID + '">' + d.ModelName + '</option>');
                });
            }
        });
  }

再次 - 这些是构建块.使用您的浏览器控制台或 Firebug 等工具查看 AJAX 请求和返回的数据,以便您可以进行适当的修改.祝你好运!

Again - these are the building blocks. Use your browser console or a tool such as Firebug to watch the AJAX request, and the returned data, so you can modify as appropriate. Good luck!

这篇关于使用 JQUERY、AJAX 和 PHP 填充选择框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆