我该如何改进这个jQuery代码?

时间:2014-12-04 20:25:13

标签: jquery mysql

我在使用jQuery方面相对较新。我编写了以下代码,该代码适用于为车辆填充一年,制造和模型的三个框的表单。当用户单击年份框时,年份在php中编码已经列出。从mysql数据库调用make和model以填充列表供他们选择。

但截至目前,对make和model的查询在填充列表之前有一点滞后。这里有什么可以改进代码的吗?在此先感谢您的帮助!

$(function(){
$('#year').change(function getmakes(){
    var vehyear = $("#year").val();
    $("#model").html('<option value="">-- All Models --</option>');
    $.ajax({
           url: "/widgets/makes.php",
           global: false,
           type: "POST",
           async: false,
           dataType: "html",
           data: "year="+vehyear, //the name of the $_POST variable and its value
           success: function (response) //'response' is the output provided
                       {
                    //counts the number of dynamically generated options
                    var dynamic_options = $("*").index( $('.dynamic')[0] );
                    //removes previously dynamically generated options if they exists (not equal to 0)
                    if (dynamic_options != (-1)) $(".dynamic").remove();
                    $("#make").html(response);
                    $(".first").attr({selected: ' selected'});

                   }
          });
          return false
});
$('#make').change(function getmodels(){
    var vehyear = $("#year").val();
    var vehmake = $("#make").val();
    $.ajax({
           url: "/widgets/models.php",
           global: false,
           type: "POST",
           async: false,
           dataType: "html",
           data: "year="+ vehyear+"&make="+vehmake, //the name of the $_POST variable and its value
           success: function (response) //'response' is the output provided
                       {
                     //counts the number of dynamically generated options
                    var dynamic_options = $("*").index( $('.dynamic')[0] );
                    //removes previously dynamically generated options if they exists (not equal to 0)
                    if (dynamic_options != (-1)) $(".dynamic").remove();
                    $("#model").html(response);
                    $(".first").attr({selected: ' selected'});                        
                   }
          });
          return false
});              

});

0 个答案:

没有答案