1

我有一组 5 个 HTML 下拉列表,它们充当过滤器,用于缩小从 mySQL 数据库返回的结果。三个相关的过滤器分别用于“Province”、“Region”和“City”的选择。

我有三个功能:

  1. findSchools(),它在任何过滤器(标记为 CSS 类.filter)发生更改时运行,并通过 AJAX 从 PHP 脚本中获取结果。完成后,将调用另外两个函数...

  2. changeRegionOptions(),在更改“省”过滤器时,并使用与第一个函数相同的方法更新可用选项,但发布到不同的脚本。

  3. changeCityOptions(),如果“区域”过滤器被更改,则运行,并更新选项,再次使用相同的方法。

问题是,由于我希望这些 AJAX 函数同时运行,并且它们本质上是异步运行的,所以我尝试使用$.when它来控制函数的执行,但这并不能解决问题。

函数运行,但 Region 和 City 过滤器返回空白(无选项);FireBug 报告显示绝对没有输出,即使 POST 请求通过。filter_province 的已发布参数正常发送,但 region 的参数在最后被切断 - 它发送为filter_region=,没有传递任何值。所以我假设我的逻辑在某个地方是错误的。代码如下:

// When any of the filters are changed, let's query the database...
$("select.filter").change(function() {
    findSchools();
});

  // First, we see if there are any results...
      function findSchools() {

          var sch_province = document.filterform.filter_province.value;
          var sch_region = document.filterform.filter_region.value;
          var sch_city = document.filterform.filter_city.value;
          var sch_cat = document.filterform.filter_category.value;
          var sch_type = document.filterform.filter_type.value;

          $.post("fetch_results.php",
          { filter_province : sch_province,
            filter_region : sch_region,
            filter_city : sch_city,
            filter_category : sch_cat,
            filter_type : sch_type },

            function(data) {

              $("#results").html("");
              $("#results").hide();
              $("#results").html(data);
              $("#results").fadeIn(600);
            }
          );

    // Once the results are fetched, we want to see if the filter they changed
       was the one for Province, and if so, update the Region and City options
        to match that selection...

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

                $.when(findSchools())
                .done(changeRegionOptions());

                $.when(changeRegionOptions())
                .done(changeCityOptions());
        });
  };

这只是我尝试解决的方法之一;我尝试使用 IF 语句,并尝试直接在通用select.filter.change()函数中调用函数(在 之后findSchools();),但它们都返回相同的结果。

对此的任何帮助都会很棒!

4

2 回答 2

0

Try this .hope this is what you were expecting. jsfiddle->sample code

于 2012-07-09T05:15:53.427 回答
0

您需要将 async 设置为 false。之后,您的代码将逐行执行。

例如像这样,在调用 $.post 之前

$.ajaxSetup({async:false});
于 2012-07-08T21:11:31.670 回答