jQueryAJAX调用来自1脚本中的多个输入字段


jQuery AJAX call from multiple input fields within the 1 script

我正在编写我的第一个HTML表单,该表单使用jQuery执行AJAX HTTP POST。当用户对输入文本字段进行更改并在字段外制表时,它会触发AJAX脚本,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>

我基本上需要分支并向editProject.php脚本传递一个额外的POST参数,这样它就知道要更新哪个数据库字段,然后有条件地向相应的行添加一个类。

当我试图让脚本分支或传递基于正在编辑的输入字段的参数时,我所尝试的一切都会破坏脚本。我还没有找到任何例子来显示由不同输入字段调用的一个脚本的正确语法——我认为这是可能的,而不是让同一脚本的多个版本作用于不同的字段。

这适用于多个字段。只需从不同的输入字段调用相同的函数。我刚把你的代码分成两部分。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>

您只需尝试发布一个值。例如CCD_ 1。其中应该包含一些用于识别ajax调用的值。

如果是用于登录,则添加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(){

您可以使用:inputclass执行类似的操作,因为它们都具有

$(":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来执行不同的查询,具体取决于哪个id被发送到php

这里有一个jsfiddle展示了它是如何工作的