我有一个简单的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>
在同一页面我有另一个需要提交的表格,所以我不知道如何做到这与我已经使用的这个功能没有冲突? 顺便说一下,它不会在同一个php文件中处理它将使用另一个文件
答案 0 :(得分:1)
我不明白有什么意义。提交多个表单有什么问题?您正在通过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在整个文档中是唯一的,这就可以了。
BTW我强烈建议您使用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();
});
});
});