gpt4 book ai didi

php - 使用 Ajax 和 php 同一页面发布多种表单

转载 作者:行者123 更新时间:2023-12-01 05:05:11 25 4
gpt4 key购买 nike

我有一个简单的ajax脚本,可以毫无问题地将数据发送到php文件索引.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>

在同一页面中,我有另一个需要提交的表单,所以我不知道如何在不与我已经使用的这个功能发生冲突的情况下执行此操作?顺便说一句,它不会在同一个 php 文件中进行处理,它将使用另一个文件

最佳答案

我不明白这有什么意义。您在提交多份表格时遇到什么问题?您正在通过 id 引用元素。

请注意,您确实应该更改代码以拦截 $('#form-id').submit(),而不是 $('#submit').click 事件,因为表单也可以使用 Enter 键或通过 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 在整个文档中是唯一的,这就会起作用。

顺便说一句,我强烈建议您使用this wonderful plugin管理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();
});
});
});

关于php - 使用 Ajax 和 php 同一页面发布多种表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6576270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com