使用jQuery和PHP序列化和提交表单
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用jQuery和PHP序列化和提交表单,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2131字,纯文字阅读大概需要4分钟。
内容图文
我正在尝试使用jQuery发送表单的数据.但是,数据无法到达服务器.你能告诉我我做错了什么吗?
我的HTML表单:
<form id="contactForm" name="contactForm" method="post">
<input type="text" name="nume" size="40" placeholder="Nume">
<input type="text" name="telefon" size="40" placeholder="Telefon">
<input type="text" name="email" size="40" placeholder="Email">
<textarea name="comentarii" cols="36" rows="5" placeholder="Message"></textarea>
<input id="submitBtn" type="submit" name="submit" value="Trimite">
</form>
JavaScript(与上面的表格在同一个文件中):
<script type="text/javascript">
$(document).ready(function(e) {
$("#contactForm").submit(function() {
$.post("getcontact.php", $("#contactForm").serialize())
// Serialization looks good: name=textInNameInput&&telefon=textInPhoneInput etc
.done(function(data) {
if (data.trim().length > 0) {
$("#sent").text("Error");
} else {
$("#sent").text("Success");
}
});
return false;
})
});
</script>
服务器端PHP(/getcontact.php):
$nume = $_REQUEST["nume"]; // $nume contains no data. Also tried $_POST
$email = $_REQUEST["email"];
$telefon = $_REQUEST["telefon"];
$comentarii = $_REQUEST["comentarii"];
你能告诉我我做错了什么吗?
UPDATE
检查var_dump($_ POST)并返回一个空数组.
奇怪的是,在我的本地机器上测试的相同代码工作正常.
如果我在托管空间上传文件,它就会停止工作.我尝试不使用jQuery做一个老式的表单,所有数据都是正确的.
我不知道这将是一个服务器配置问题.有任何想法吗?
谢谢!
解决方法:
您可以使用此功能
var datastring = $("#contactForm").serialize();
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handling here');
}
});
返回类型是json
编辑:我使用event.preventDefault来防止浏览器在这种情况下提交.
在答案中添加更多数据.
dataType:“jsonp”如果是跨域调用.
beforeSend://这是一个预请求回调函数
complete://在请求结束后调用的函数.无论成功与否,必须执行的代码都可以在这里
async://默认情况下,所有请求都是异步发送的
cache://默认为true.如果设置为false,它将强制浏览器不缓存请求的页面.
查找官方页面here
内容总结
以上是互联网集市为您收集整理的使用jQuery和PHP序列化和提交表单全部内容,希望文章能够帮你解决使用jQuery和PHP序列化和提交表单所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。