使用Jquery将HTML表单发布数据发送到文件? [英] Send HTML form post data to file with Jquery?
问题描述
我正在尝试使用jQuery将帖子数据发送到名为 postinfo.php
的帖子数据文件处理程序,但到目前为止我可以制作它。
I am trying to send post data to my post data file handler called postinfo.php
with jQuery but so far I can make it.
这是我的post.php代码:
Here is my post.php code:
<HTML>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<script type="text/javscript">
$('#form_id').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "http://www.vemvo.com/test/postinfo.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
});
</script>
<form method="post" id="form_id">
<input type="text" name="ime">
<input type="submit" id="submit" name="submit" value="Send">
</form>
您可以在此处查看页面: http://www.vemvo.com/test/post.php
You can see the page here: http://www.vemvo.com/test/post.php
这是来自postinfo.php的代码:
Here is the code from my postinfo.php:
<?PHP
$ime = $_POST['ime'];
echo "Your name is $ime";
?>
这里位于postinfo.php - http://www.vemvo.com/test/postinfo.php
Here is located postinfo.php - http://www.vemvo.com/test/postinfo.php
那么在哪里我的错误以及如何让它发挥作用?
现在它没有发送数据而没有给我成功警报。
So where is my mistake and how I can make it work? Now it's not sending the data and not giving me the success alert.
推荐答案
你的jQuery选择器不会出现找到该表单,因为选择器在DOM中存在表单
标记之前运行。尝试将其包装在jQuery函数中以等待文档准备就绪:
Your jQuery selector isn't going to find that form, since the selector is running before the form
tag exists in the DOM. Try wrapping it in the jQuery function to wait for the document to be ready:
$(function () {
$('#form_id').on('submit', function(e){
// the rest of your code
});
});
返回false $ c $也许是个好主意c>最后,进一步抑制表单的默认后期操作:
It also might be a good idea to return false
at the end, to further suppress the form's default post action:
e.preventDefault();
$.ajax({
type: "POST",
url: "./postinfo.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
return false;
目前表格正常发布。由于AJAX处理程序从不附加(因为当选择器执行时元素不存在),它只是做一个普通的文档级表单发布。由于表单
标记中没有指定 action
属性,因此该页面默认发布到自身。只响应当前页面。
Currently the form is posting as normal. Since the AJAX handler is never attached (because the element doesn't exist when the selector executes), it's just doing a normal document-level form post. And since there's no action
attribute specified in the form
tag, the page is posting to itself by default. Which just responds with the current page.
编辑:您还有一个错字,可能会阻止浏览器执行您的JavaScript代码:
You also have a typo which may be preventing the browser from executing your JavaScript code at all:
<script type="text/javscript">
你错过了第二个a。这应该是:
You're missing the second "a". This should be:
<script type="text/javascript">
这篇关于使用Jquery将HTML表单发布数据发送到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!