当我通过 Ajax 向 PHP 脚本提交联系表单时遇到问题。我以前使用过 jQuery/Ajax 函数以及联系脚本,但是在这种情况下,进程运行到 ajax 请求,然后返回错误:空字符串。
$(document).ready(function(){
jQuery("#sendmail").click(function(){
var name = $("#name").val();
var phone = $("#phone").val();
var email = $("#email").val();
var text = $("#message").val();
//var datastr ='name=' + name + '&mail=' + mail + '&subject=' + subject + '&text=' + text;
var datastr ='name=' + name + '&phone=' + phone + '&email=' + email + '&text=' + text;
$("#form-div").css("float", "left");
$("#form-div").html("<p>Thank you for contacting Stillframe Photography.</p><p>Please wait for just a few moments while your enquiry is being sent.</p>");
$("#form-div").fadeIn("slow");
alert(datastr);
jQuery.ajax({
type: "POST",
url: "contact.script.php",
data: datastr,
success: function(html){
$("#response").fadeIn("slow");
$("#response").html(html);
//setTimeout('$("#response").fadeOut("slow")',2000);
}
,error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#response").html('there was an error');
console.log('error thrown');
console.log(errorThrown);
}
});
});
});
您可以在http://www.stillframe.com.au/test.php看到正在运行的页面您可以在上面的相同链接处看到没有页面媒体的表单,但 test2.php
我还在同一个 url 中添加了没有任何其他 jQuery 的脚本,但 test3.php 直接发布到联系人 PHP 脚本以确认该脚本中没有错误。
已解决:从头部删除了基本 href 标签,脚本现在可以正常工作。
最佳答案
不是逐个字段地使用,而是使用表单 ID <form id="myform">
并将其序列化。试试这个:
$(document).ready(function(){
jQuery("#sendmail").click(function(){
jQuery.ajax({
type: "POST",
url: "contact.script.php",
data: $('#myform').serialize(),
cache: false,
success: function(output) {
$("#form-div").css("float", "left");
$("#form-div").html("<p>Thank you for contacting Stillframe Photography.</p><p>Please wait for just a few moments while your enquiry is being sent.</p>");
$("#form-div").fadeIn("slow");
$("#response").html(output);
$("#response").fadeIn("slow");
//setTimeout('$("#response").fadeOut("slow")',2000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#response").html('there was an error');
console.log('error thrown');
console.log(errorThrown);
}
});
});
});
关于php - jQuery AJAX 表单错误。空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7198213/