簡體   English   中英

無法在AJAX響應中獲取HTML select的值

[英]Can't get the value of HTML select in AJAX response

我的代碼有兩個步驟。 第一步,用戶填寫一些字段,然后將數據由Ajax提交到服務器。 Ajax返回一個HTML選擇輸入,用戶必須選擇一個值。 這是第二步。

問題是,當我嘗試獲取javascript中select的值時,顯示為null。

我用來獲取選擇值的代碼在正常情況下有效。 但是當用ajax檢索select時,就會出現此問題。

獲取選擇值的代碼

var e = document.getElementById("ordernum");
var num = e.options[e.selectedIndex].value;

這是一個示例HTML文件,該文件顯示了如何動態生成select元素並通過event.target.value在其onchange事件上從中獲取值:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script>
            const GameDifficulty = {
                EASY:1,
                MEDIUM:2,
                HARD:3,
                INSANE:4
            };

            function init(event) {
                console.log(event);
                var body = document.getElementById('body');
                var select = document.createElement('select');
                select.id = 'selDifficulty';
                for (var diff in GameDifficulty) {
                    var option = document.createElement('option');
                    option.value = GameDifficulty[diff];
                    option.innerHTML = diff;
                    select.appendChild(option);
                }

                select.onchange = test;

                body.appendChild(select);
                console.log(body);
            }

            function test(event) {
                console.log(event.target.value);
            }

            window.onload = init;
        </script>
    </head>
    <body id="body">
    </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM