简体   繁体   English

如何使用PHP中的数据填充jQuery中的选择列表?

[英]How do I populate a select list in jQuery with data from PHP?

I have a bunch of courses and each course has a different number of lessons. 我有一堆课程,每门课程都有不同数量的课程。 So, I have two select lists one for courses and one for the lessons associated with that course. 因此,我有两个选择列表,一个用于课程,一个用于与该课程相关的课程。 The course select list is easy, I'm doing that from the back end of PHP in a foreach loop. 课程选择列表很简单,我是通过PHP的foreach循环后端来完成的。 I'm going through all the courses that a student has: 我正在学习一个学生的所有课程:

public function createContent($student)
{
//get student courses
//get lessons of each course
//get the upcoming lessons
 $lessons = $this->getLessons($courses); //need to make use of $lessons to populate lesson list

        foreach($courseArray as $c)
        {               
            $courseSelectList .= '<option id="select"'.$count.' value="'.$c['id'].'">'.$c['fullname'].'</option>';
            $count++;           
        }
//create a Lesson select list in php backend or do it in the front end dynamically with jQuery?
        return $courseSelectList.$lessonSelectList;
}

My next step is to create a second select list that contains the lessons of the selected course. 我的下一步是创建第二个选择列表,其中包含所选课程的课程。 How this list is populated depends on what the student selects in the course select list. 如何填充此列表取决于学生在课程选择列表中选择的内容。 All this is dynamic and depends on the student so the courses (and thus the lessons) in the course select list is different for each student and is retrieved from the database. 所有这些都是动态的,并且取决于学生,因此课程选择列表中的课程(以及课程)对于每个学生都是不同的,并且可以从数据库中检索。 Given the student and course, I know which lessons should be in the lesson select list. 给定学生和课程,我知道哪些课程应该在课程选择列表中。 The lessons are retrieved after I first retrieve the courses of the student as shown in the comments in the code below. 在我第一次检索学生的课程之后,就检索了课程,如下面的代码中的注释所示。 I just need a way to populate the lesson select list according to what the student selects. 我只需要一种根据学生的选择来填充课程选择列表的方法。

How should I go about doing this? 我应该怎么做呢? Any help would be great. 任何帮助都会很棒。 Bear in mind I'm a beginner jQuery user. 请记住,我是jQuery初学者。

I found a very useful and simple jQuery plugin, 我发现了一个非常有用且简单的jQuery插件,

http://codeassembly.com/Simple-chained-combobox-plugin-for-jQuery/ http://codeassembly.com/Simple-chained-combobox-plugin-for-jQuery/

You will need to issue an AJAX request based upon the value of the selected course. 您将需要根据所选课程的值发出AJAX请求。 I am assuming below that the id of the course select is 'courseSelect': 我在下面假设课程选择的ID为“ courseSelect”:

$('#courseSelect').bind('change', function() {
    var _t = $(this);
    var val = _t.val();
    $.ajax({
        url: '/path/to/script.php',
        data: 'c='+val,
        success: function(html) {
            $('#lessonSelect').html(html);
        }
    });
});

The strategy behind this is that your 'script.php' is called once a different option is selected for the courses. 其背后的策略是,一旦为课程选择了其他选项,就会调用您的“ script.php”。 'script.php' will be sent the value of the option by the browser and can be accessed as $_GET['c'] . 'script.php'将由浏览器发送该选项的值,并且可以作为$_GET['c'] The success function will be called once the request returns, and the html parameter will be set equal to everything that you output inside of script.php (via echo , print , error statements issued by PHP, all output). 请求返回后,将调用成功函数,并且html参数将设置为等于您在script.php内部输出的所有内容 (通过echoprint ,PHP发出的错误语句以及所有输出)。

In this sense your script.php will simply select the list of lessons from your database for the given course, and just output all of the <option value = 'Lesson Key'>Lesson</option> markup. 从这种意义上讲,您的script.php只需从数据库中为给定课程选择课程列表,然后仅输出所有<option value = 'Lesson Key'>Lesson</option>标记。 Since the output of the server-side script is HTML markup, I named the parameter to the success function html . 由于服务器端脚本的输出是HTML标记,因此我将参数命名为成功函数html

script.php script.php

<?php
    // Validate existence and proper type of input variable
    // I am assuming here that the 'value' for the option for each course is an
    // integer primary key for a table in your database
    if(!isset($_GET['c']) || !is_numeric($_GET['c']))
        exit();
   $course = intval( $_GET['c'] );
   // Select all of the lessons for the selected course from your database 
   // and output them as HTML Option elements.
?>

Arguably the simplest way to do it (from a jQ point of view, at least) is to call .load() and generate the HTML on the server side. 可以说,最简单的方法(至少从jQ的角度来看)是调用.load()并在服务器端生成HTML。

For example, lets say that you existing PHP code generates the following HTML: 例如,假设您现有的PHP代码生成以下HTML:

<select id="select_1">
  <option value="0">Please select...</option>
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
</select>
<div id="container_for_select_2"></div>

Now we attach a change event to this select, and load the next select into the container <div> : 现在,我们将一个change事件附加到此select上,并将下一个select加载到容器<div>

<script type="text/javascript">

  $("#select_1").change(function() {

    // Get the value of the option that was chosen
    // You could also do: var currentValue = this.options[this.selectedIndex].value;
    var currentValue = $(this).val();

    // Don't do anything if the "Please select" option was chosen
    if (currentValue == '0') {
      return;
    }

    // Load some data from the server into the next <div>
    $("#container_for_select_2").load('getselect.php?option='+currentValue);

  });

</script>

So now, in getselect.php we can do something like this: 现在,在getselect.php我们可以执行以下操作:

<?php

  switch ($_GET['option']) {
    case 1:
      echo '<select><option value="1">An option</option><option value="2">Another option</option></select>';
      break;
    case 2:
      echo '<select><option value="3">An option</option><option value="4">Another option</option></select>';
      break;

    // ...etc...

  }

?>

I am not going to write the code for you, from a very high level this is how i would do it without plugins: create a page that returns a list of your lessons from a database or wherever they are stored, based on which course id is passed to it. 我不会为您编写代码,从非常高的层次上讲,这就是我不使用插件的方式:创建一个页面,该页面根据课程ID返回数据库或存储位置的课程列表被传递给它。 create a javascript (or jquery) ajax method on your page that passes your course id to this page and clears and creates the lessons dropdown from the returned data (JSON format is good for the returned data). 在页面上创建一个javascript(或jquery)ajax方法,将您的课程ID传递到此页面,并从返回的数据中清除并创建课程下拉列表(JSON格式非常适合返回的数据)。 Call the ajax method whenever the change event is fired on your course dropdown. 每当在课程下拉列表中触发change事件时,都调用ajax方法。 look at: 看着:

http://api.jquery.com/jQuery.ajax/ http://api.jquery.com/jQuery.ajax/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM