簡體   English   中英

1個腳本中來自多個輸入字段的jQuery AJAX調用

[英]jQuery AJAX call from multiple input fields within the 1 script

我正在處理我的第一個使用jQuery執行AJAX HTTP POST的HTML表單。 當用戶更改輸入文本字段並在該字段外進行制表時,它將觸發AJAX腳本,該腳本隨后調用執行數據庫更新的PHP腳本。

我已經在我的第一個輸入字段中成功完成了此工作-現在,我想將其擴展到第二,第三等輸入字段,但希望嘗試避免使用多個腳本執行非常相似的功能。 我是jQuery和AJAX的新手,因此可以隨時學習語法。

這是我的輸入字段:

經理電話

這是我在storeManager輸入字段上運行的Javascript:

<script type="text/javascript">
   $(document).ready(function() {
    $("#storeManager").change(function(){
        var storeManager = $("#storeManager").val();
        $.post('editProject.php', { storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
            $("#managerRow").addClass("success");

        }).fail(function () {
            // no data available in this context
            $("#managerRow").addClass("danger");
            $("#ajaxAlert").addClass("alert alert-danger");
        });
     }); 
});
</script>

我本質上需要分支並將附加的POST參數傳遞給editProject.php腳本,以便它知道要更新哪個數據庫字段,然后有條件地將一個類添加到適當的行。

我嘗試過的所有事情都會在嘗試使腳本分支或根據正在編輯的輸入字段傳遞參數時破壞腳本。 我還沒有找到任何顯示正確語法的示例,以使一個腳本被不同的輸入字段調用-我想這是可能的,而不是讓同一腳本的多個版本作用於不同的字段。

您可以使用:input或它們都具有的class來做類似的事情

$(":input").on("change", function(){
    var text = $(this).val();
    var idOfInput = $(this).attr("id");

    //your post to php function using the above variables

});

由此,您可以使用idOfInput變量將輸入的id發布到您的php腳本中,然后您可以在php端使用case switch根據發送到php的id進行不同的查詢

這是一個顯示它如何工作的jsfiddle

您只是嘗試發布一個值。 例如type 其中應包含一些用於標識ajax調用的值。

如果用於登錄,則添加type = 'login'. Then check the value of $_POST['type'] and write php according to it type = 'login'. Then check the value of $_POST['type'] and write php according to it

sample.php

if(isset($_POST['type']))
{
    if($_POST['type'] == 'login')
    {
        //your code goes here
    }
}

您可以使用這種代碼:

$("#storeManager, #Manager, #Phone").change(function(){

這適用於多個字段。 只需從不同的輸入字段調用相同的函數即可。 我只是將您的代碼分為兩部分。 1.每個字段的onChange函數,以及2.通過傳遞字段參數來調用函數。

<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){ yourFunction(this) }):

$("#worker").change(function(){ yourFunction(this) }):

$("#someX").change(function(){ yourFunction(this) }):

yourFunction(field)
{
    var value = $(field).val();
    var inputId=field.id;
    $.post('editProject.php', { inputValue: value, id: inputId }, function(data) {
        $('#'+inputId+'Row').addClass("success"); // (this looks like: *#storeManagerRow* ) you can change your Row id's accordingly to make your work easier. Eg: for **#storeManager** make this id as **storeManagerRow**

    }).fail(function () {
        // no data available in this context
        $('#'+inputId+'Row').addClass("danger");
        $("#ajaxAlert").addClass("alert alert-danger");
    });

});
</script>

暫無
暫無

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

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