小编典典
您的代码几乎没有问题,例如:
…它只会得到未定义的索引:sessions.php中的用户名
问题是由于以下两行,
contentType : false,
processData: false,
的contentType (默认值:'application/x-www-form-urlencoded; charset=UTF-8')
类型:Boolean或者String
当发送数据到服务器时,使用该内容类型。默认值为“ application / x-www-form-urlencoded; charset =
UTF-8”,在大多数情况下都可以。如果您将内容类型显式传递给$.ajax(),则该内容类型将始终发送到服务器(即使没有发送数据)。从jQuery
1.6开始,您可以通过false告诉jQuery不要设置任何内容类型标头。
和
过程数据 (默认值:true)
类型:Boolean
默认情况下,数据到数据选项传递作为一个对象(在技术上,不是字符串其它任何东西)将被处理并转换成一个查询字符串,以适应默认 内容类型“应用程序/ x
-www-form-urlencoded” 。如果要发送DOMDocument或其他未处理的数据,请将此选项设置为false。
Hence, $_POST array would be empty in sessions.php page if you set
contentType and processData to false, and that’s why you’re getting this
undefined index: username error. But having said that, since you’re sending
a file with your AJAX request, it’s okay to set these settings as false,
which is further explained in the following point.
.serialize()方法创建通过串行化形式的控制值,如一个URL编码的文本串,和。但是,序列化表单时它不包含文件输入字段,因此您的远程AJAX处理程序将根本不会收到文件。因此,如果要通过AJAX上传文件,请使用FormData对象。但是请记住,旧的浏览器不支持FormData对象。FormData支持从以下桌面浏览器版本开始:IE 10 +,Firefox 4.0 +,Chrome 7 +,Safari 5 +,Opera 12+。
由于您期望服务器提供json对象,因此请将此设置添加dataType:'json'到您的AJAX请求中。dataType是您期望从服务器返回的数据类型。
所以解决方案是这样的:
保持 HTML 表单不变,并通过以下方式更改 jQuery / AJAX 脚本,
$('#confirm').click(function(e){
e.preventDefault();
var formData = new FormData($('form')[0]);
$.ajax({
type: 'POST',
url : 'sessions.php',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(d){
console.log(d.message);
}
});
});
然后在 sessions.php 页面上,像这样处理表单:
$exist = "david";
if(isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['pass']) && !empty($_POST['pass'])){
if($_POST['username'] == $exist){
echo json_encode(array("message" => "Already exist"));
}else{
echo json_encode(array("message" => "You can succesfully add"));
// get username and password
$username = $_POST['username'];
$password = $_POST['pass'];
// process file input
// Check whether user has uploaded any file or not
if(is_uploaded_file($_FILES['fileupload']['tmp_name'])){
// user has uploaded a file
}else{
// no file has been uploaded
}
}
}else{
echo json_encode(array("message" => "Invalid form inputs"));
}
?>
2020-07-26