我无法通过Ajax创建的select元素设置值或获取值

时间:2022-10-07 17:48:17

I created "omarkasec" as a function and I get car brands from database via ajax and I added at the select element this car brands as options via ajax --> success. But I can't set a value this select element.

我创建了“omarkasec”作为一个功能,我通过ajax从数据库获得汽车品牌,我在select元素中添加了这个汽车品牌作为选项通过ajax - >成功。但是我无法为这个select元素设置一个值。

I tried this codes for set value:

我尝试使用此代码设置值:

  1. $('select[name=marka]').val('Lada');
  2. $( '选择[名称=马尔卡]')VAL( '拉达');
  3. $('select[name=marka] option[value=Lada]').prop('selected', true);
  4. $('select [name = marka] option [value = Lada]')。prop('selected',true);
  5. $('select[name=marka] option[value=Lada]').attr('selected', 'selected');
  6. $('select [name = marka] option [value = Lada]')。attr('selected','selected');

this codes don't work. But if I add alert(""); in "omarkasec" function the codes do work and if I remove alert(""); the codes don't work.

这些代码不起作用。但是如果我添加警报(“”);在“omarkasec”功能中,代码可以正常工作,如果我删除警告(“”);代码不起作用。

<div id="marka" class="gizle" >
   Marka: <br>
   <select name="marka" onchange="omodelsec()" size="10" ></select>
</div>

<script language='javascript' type='text/javascript'>
    function omarkasec() {
        $.ajax({
            type: "POST",
            url: "aracsor.php",
            dataType: "json",
            data: {
                otomobilmodelyili : $("select[name=modelyili]").val(), //This work, because i created php.
            },
            success: function(donen){
                $("#marka").removeClass("gizle");
                $("#model").addClass("gizle");
                $("#yakit").addClass("gizle");
                $("#sanziman").addClass("gizle");
                $("#cekis").addClass("gizle");
                $("#kasatipi").addClass("gizle");
                $("select[name=marka]").empty();
                $.each(donen, function (index, otomarka) {
                    $("select[name=marka]").append($("<option>", {
                        text : otomarka,
                        value  : otomarka,
                    }));
                });
            },
        });
     //if I add here alert(""); The following code works.
    }
    </script>

<script language='javascript' type='text/javascript'>
   omarkasec();
   $('select[name=marka]').val('Lada');
   alert($('select[name=marka]').val()); //if I add alert(""); this code work but if I remove alert(""); this code get null value.
</script>

2 个解决方案

#1


1  

Ajax calls are asynchronous. Your code executes the $.ajax() call passing it a call back function, but that call back function is not executed at that very moment.

Ajax调用是异步的。你的代码执行$ .ajax()调用,传递一个回调函数,但那个回调函数不会在那个时刻执行。

The execution immediately proceeds the the statement after $.ajax() but at that moment the content has not been loaded.

执行会立即在$ .ajax()之后继续执行该语句,但此时内容尚未加载。

However, if you perform an alert(), the call back might eventually be triggered while the alert dialog is open, and thus content is loaded by your call back function. If you then close the popup, any code following it will find the content is there.

但是,如果执行alert(),则在警报对话框打开时最终可能会触发回调,因此内容将由您的回调函数加载。如果您随后关闭弹出窗口,则其后面的任何代码都会找到内容。

One way to solve this, is to use the return value of the $.ajax call, which is a promise, and chain a then call to it:

解决此问题的一种方法是使用$ .ajax调用的返回值,这是一个promise,然后链接a调用它:

function omarkasec(oncomplete) {
    return $.ajax({
//  ^^^^^^
        type: "POST",
        url: "aracsor.php",
        dataType: "json",
        data: {
            otomobilmodelyili : $("select[name=modelyili]").val(),
        },
        success: function(donen){
            $("#marka").removeClass("gizle");
            $("#model").addClass("gizle");
            $("#yakit").addClass("gizle");
            $("#sanziman").addClass("gizle");
            $("#cekis").addClass("gizle");
            $("#kasatipi").addClass("gizle");
            $("select[name=marka]").empty();
            $.each(donen, function (index, otomarka) {
                $("select[name=marka]").append($("<option>", {
                    text : otomarka,
                    value  : otomarka,
                }));
            });
        },
    });
}

// provide (anonymous) callback function to the `then` method: 
omarkasec.then(function () {
     // this code will only be executed when content is loaded:
     $('select[name=marka]').val('Lada');
     alert($('select[name=marka]').val());
});

#2


1  

You have a race condition. You are calling omarkasec() and not waiting for it to finish to execute the select.val() action. When you add the alert it "works" because it gives the code some extra time to complete the ajax call an fill the values. When you alert it, the values are already filled.

你有竞争条件。您正在调用omarkasec()而不是等待它完成执行select.val()操作。当您添加警报时它“起作用”,因为它为代码提供了一些额外的时间来完成ajax调用以填充值。当您提醒它时,值已经填满。

All your code that depends on the result from the ajax call must be inside the success callback.

依赖于ajax调用结果的所有代码都必须在成功回调中。

#1


1  

Ajax calls are asynchronous. Your code executes the $.ajax() call passing it a call back function, but that call back function is not executed at that very moment.

Ajax调用是异步的。你的代码执行$ .ajax()调用,传递一个回调函数,但那个回调函数不会在那个时刻执行。

The execution immediately proceeds the the statement after $.ajax() but at that moment the content has not been loaded.

执行会立即在$ .ajax()之后继续执行该语句,但此时内容尚未加载。

However, if you perform an alert(), the call back might eventually be triggered while the alert dialog is open, and thus content is loaded by your call back function. If you then close the popup, any code following it will find the content is there.

但是,如果执行alert(),则在警报对话框打开时最终可能会触发回调,因此内容将由您的回调函数加载。如果您随后关闭弹出窗口,则其后面的任何代码都会找到内容。

One way to solve this, is to use the return value of the $.ajax call, which is a promise, and chain a then call to it:

解决此问题的一种方法是使用$ .ajax调用的返回值,这是一个promise,然后链接a调用它:

function omarkasec(oncomplete) {
    return $.ajax({
//  ^^^^^^
        type: "POST",
        url: "aracsor.php",
        dataType: "json",
        data: {
            otomobilmodelyili : $("select[name=modelyili]").val(),
        },
        success: function(donen){
            $("#marka").removeClass("gizle");
            $("#model").addClass("gizle");
            $("#yakit").addClass("gizle");
            $("#sanziman").addClass("gizle");
            $("#cekis").addClass("gizle");
            $("#kasatipi").addClass("gizle");
            $("select[name=marka]").empty();
            $.each(donen, function (index, otomarka) {
                $("select[name=marka]").append($("<option>", {
                    text : otomarka,
                    value  : otomarka,
                }));
            });
        },
    });
}

// provide (anonymous) callback function to the `then` method: 
omarkasec.then(function () {
     // this code will only be executed when content is loaded:
     $('select[name=marka]').val('Lada');
     alert($('select[name=marka]').val());
});

#2


1  

You have a race condition. You are calling omarkasec() and not waiting for it to finish to execute the select.val() action. When you add the alert it "works" because it gives the code some extra time to complete the ajax call an fill the values. When you alert it, the values are already filled.

你有竞争条件。您正在调用omarkasec()而不是等待它完成执行select.val()操作。当您添加警报时它“起作用”,因为它为代码提供了一些额外的时间来完成ajax调用以填充值。当您提醒它时,值已经填满。

All your code that depends on the result from the ajax call must be inside the success callback.

依赖于ajax调用结果的所有代码都必须在成功回调中。