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

查看:121
本文介绍了使用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调用的成功方法中重新填充?

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?

任何帮助将非常感谢, p>

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天全站免登陆