繁体   English   中英

AJAX加载选择,按值选择选项

[英]AJAX loaded select, select option by value

如果选择是通过 AJAX 加载的,如何按值选择选项

索引.php

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
    <div id="data"></div>
</body>

<script>
function LoadSelect() {

    var post_data = {
        token: "test"
    };

    $.ajax({
        type: 'POST',
        url: 'load_select.php',
        data: post_data,
        dataType: "json",
        beforeSend: function() {},
        success: function(data) {
            $("#data").html(data["msg"]);
        },
        complete: function() {}
    });
}
$(document).ready(function() {
    LoadSelect();
});
</script>

</html>

load_select.php

<?php

// Value from the database
$gender = "female";

$html = '

<select class="form-control" id="gender" name="gender">
    <option value="female">Female</option>
    <option value="male">Male</option>
</select>

<script>
$("#gender").val("'.$gender.'");
</script>

';

echo json_encode(array('msg' => $html));

试过这段代码,但它不起作用。

问题解决了,$gender 变量从数据库中得到了错误的值,比如“f”而不是“female”。

如果我理解正确,那么您将使用 ajax 请求中的 html 覆盖选择。 为了保持该值,您需要存储原始值,然后覆盖 html,然后恢复原始值。 请参阅下面的这个片段。

最好不要使用 ajax 调用覆盖 html 元素,而只更新需要更新的信息。

 $("#gender").val("male"); //Lets pretend this onclick handler is your ajax succes handler. $('#MimicAjax').on('click', function(){ //Fake ajax result for demonstraion purpose var ajaxResult = '<select class="form-control" id="gender" name="gender"><option value="female">Female</option><option value="male">Male</option></select>'; //store the original value var originalValue = $("#gender").val(); //Do your ajax thingy $('#data').html(ajaxResult); //restore original value $("#gender").val(originalValue); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="data"> <select class="form-control" id="gender" name="gender"> <option value="female">Female</option> <option value="male">Male</option> </select> </div> <button id="MimicAjax">MimicAjax</button>


如果您只想在使用 ajax 添加 html 后设置该值,则只需在更改 html 后在 succes 处理程序中使用该行。

$.ajax({
    type: 'POST',
    url: 'src/ajax/load_select.php',
    data: post_data,
    dataType: "json",
    beforeSend: function() {},
    success: function(data) {
         $("#data").html(data["msg"]);
         $("#gender").val("male");
    },
    complete: function() {
    }
});

通常,通过代码更改选择的值后应触发更改事件,如下所示$("#gender").trigger('change');

暂无
暂无

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

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