我正在尝试使用Jquery和AJAX提交一个没有页面刷新的小型联系表单。我从另一个Stackoverflow线程获得了代码,但是当我尝试提交表单并单击“提交”按钮时,没有任何反应。我甚至没有在控制台上收到任何错误消息。所以任何人都可以告诉我这里我做错了什么。这是表格
<form id="contactform" name="contactForm">
<input type="text" name="name"/><br/>
<input type="text" name="email"/><br/>
<textarea name="comment">
</textarea>
<p style='text-align:right;'><input type="submit"/></p>
</form>
这是JS:
<script>
// variable to hold request
var request;
// bind to the submit event of our form
$("#contactform").submit(function(event){
// abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "form.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
</script>
最后这里是post.php文件。
<?php
echo $_POST['fullname']."<br/>";
echo $_POST['email']."<br/>";
echo $_POST['comment']."<br/>";
?>
以下是页面的网址,其格式为:http://contestlancer.com/davidicus/
如果您点击标题徽标中的小邮件图标,您将看到联系表单。
此致 艾哈迈尔
答案 0 :(得分:5)
您正在向form.php
发送请求,并且您说您的文件名为post.php
。改变这一部分:
request = $.ajax({
url: "form.php",
type: "post",
data: serializedData
});
要:
request = $.ajax({
url: "post.php",
type: "post",
data: serializedData
});