簡體   English   中英

發布多 forms 與 Ajax 和 php 同一頁

[英]post multi forms with Ajax and php same page

我有一個簡單的 ajax 腳本,它將數據發送到 php 文件,沒有問題 index.php

    <script type="text/javascript">
      $(function() {
        $('#submit').click(function() {
        $('#container').append('<img src="img/loading.gif" alt="Currently Loading" id="loading" />');

            var name = $('#name').val();
            var email = $('#email').val();
            var comments = $('#comments').val();

            $.ajax({
                url: 'submit_to_db.php',
                type: 'POST',
                data: 'name=' + name + '&email=' + email + '&comments=' + comments,

                success: function(result) {
                    $('#response').remove();
                    $('#container').append('<p id="response">' + result + '</p>');
                    $('#loading').fadeOut(500, function() {
                        $(this).remove();
                    });

                }
            });

            return false;
        });

      });
    </script>

在同一頁面中,我有另一個需要提交的表單,所以我不知道如何在不與我已經使用的 function 沖突的情況下做到這一點? 順便說一句,它不會在同一個 php 文件中處理,它將使用另一個文件

我不明白這有什么意義。 您在提交多個表格時遇到了哪些問題? 您通過 id 引用元素。

請注意,您確實應該更改代碼以攔截$('#form-id').submit() ,而不是$('#submit').click事件,因為也可以使用輸入鍵提交表單,或者通過 javascript 回調,不僅使用提交按鈕。

在你的代碼中做這樣的事情有什么問題

$(function() {
        $('#other-form-id').submit(function() {
            $.ajax({
                url: 'other-php-script.php',
                type: 'POST',
                data: 'name=' + name + '&email=' + email + '&comments=' + comments,

                success: function(result) {
                    // your success handling
                }
            });
            return false;
        });
      });

只要 Dom ID 在文檔中是唯一的,這將起作用。

順便說一句,我強烈建議您使用這個出色的插件來管理 ajax 表單,以保持您的 js 代碼更簡潔。 這樣,您的代碼可以重寫為:

$(document).ready(function() { 
        // bind 'myForm' and provide a simple callback function 
        $('#myForm').ajaxForm(function() { 
            $('#response').remove();
            $('#container').append('<p id="response">' + result + '</p>');
            $('#loading').fadeOut(500, function() {
                $(this).remove();
            });                
        }); 
    }); 

暫無
暫無

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

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