使用 jquery ajax 的下拉列表中的单个值

Individual values in a dropdownlist using jquery ajax

我得到了一个下拉列表,它使用 jquery ajax 过滤结果。但我不知道如何分隔列表中的值。

当我使用这段代码时:

$("#orderby").on('change', function() {

    $.post("ajax/prijslaaghoog.php", $("#orderby").val('lowhigh'), function(result){
        $("#productviewajax").html(result);
    });

    $.post("ajax/default.php", $("#orderby").val('default'), function(result){
        $("#productviewajax").html(result);
    });
});

当我 select 一个值时,它会运行两个 php 文件。我怎样才能做到只有 default.php 在默认为 selected 时运行,而 prijslaaghoog.php 在 lowhigh 为 selected 时运行?

提前致谢

尝试将 if 子句放在 $.post 之前,如下所示:

$("#orderby").on('change', function() {
    if ($('#orderby').val() == 'lowhigh'){
        //post here.
    }else if ($('#orderby').val() == 'default'){
        //post here
    }
});

按如下操作:

 $("#orderby").on('change', function() {
     if ($(this).val() == 'lowhigh'){
        $.post("ajax/prijslaaghoog.php", $("#orderby").val('lowhigh'), function(result){
            $("#productviewajax").html(result);
        });
     }else if ($(this).val() == 'default'){
       $.post("ajax/default.php", $("#orderby").val('default'), function(result){
            $("#productviewajax").html(result);
        });
    }
});

使用 $("#orderby").val('lowhigh') 设置下拉列表的值。 相反,您应该过滤所选的选项:

$("#orderby").on('change', function() {

    var strUrl = "ajax/default.php";
    var strFilter = $('#orderby > option').filter(':selected').val();

    if (strFilter  == 'lowhigh'){
        strUrl = "ajax/prijslaaghoog.php";
    }

    $.post(strUrl, { filter: strFilter }, function(result){
        $("#productviewajax").html(result);
    });

});

而且,如果您在每个选项中都有 data 属性,您甚至不需要 if statement:

<select id="orderby">
    <option value="default" data-post-url="default.php">Default</option>
    <option value="lowhigh" data-post-url="prijslaaghoog.php">lowhigh</option>
</select>

$("#orderby").on('change', function() {

    var option = $('#orderby > option').filter(':selected');

    $.post("ajax/" + option.data("post-url"), { 
        filter: option.val() 
    }, function(result){
        $("#productviewajax").html(result);
    });

});