簡體   English   中英

如何在另一個 select 框的 onchange 事件中使用數據庫中的值填充 select 框,而不刷新頁面或提交表單?

[英]How to fill select box with values from database on onchange event of another select box and without refreshing the page or submitting the form?

我在 php 頁面中有一個 html 表格。 演示代碼如下。

<html>
<head>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
<br>
<select name="job" >
</select>
<br>
<input name="salary" type="text">
<br>
<input name="Submit" type="submit" value="Submit">
</form>
<br>
</body>
</html>

在上面的表單中,單擊提交按鈕后,javascript 中的一些驗證代碼被執行,驗證后,表單使用 java 腳本以編程方式提交。

要求是當我 select 一個值來自第一個 select 框時; 第二個 select 框應該填充一些值。 第二個 select 框中的這些值來自數據庫。 As I dont know anything in AJAX but I want to achieve this using AJAX and javascript/jquery because whenever I select any value from first select box the form should not get submitted or the page should not get refreshed just the second select box gets filled with來自數據庫的新值。

請朋友們指導我解決這個問題。 謝謝!

HTML

<select id="job" name="job" >
</select>

jQuery

function showUser(value){

        $("#job").get(0).options.length = 0;
        $("#job").get(0).options[0] = new Option("Loading jobs", "-1"); 

        $.ajax({
            type: "POST",
            url: "Default.aspx/GetJobs",
            data: "{userID:" + value+ "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#job").get(0).options.length = 0;
                $("#job").get(0).options[0] = new Option("Select job", "-1"); 

                $.each(msg.d, function(index, item) {
                    $("#job").get(0).options[$("#job").get(0).options.length] = new Option(item.Display, item.Value);
                });
            },
            error: function() {
                $("#job").get(0).options.length = 0;
                alert("Failed to load jobs");
            }
        });
}

取自這里

暫無
暫無

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

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