这是javascript:
function eAC(emailData) {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
}
if (!httpRequest) {
return false;
}
console.log(emailData);
var fd = new FormData();
fd.append("email", emailData);
httpRequest.onreadystatechange = eAC_callback;
httpRequest.open('POST', "http://website.com/file.php");
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(fd);
}
function eAC_callback() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log(response);
} else {
return false;
}
}
};
这是php:
$pec_result = array();
if(isset($_POST['email']) && strlen($_POST['email']) > 0){
$pec_result['error'] = 'Its good';
echo json_encode($pec_result);
die();
} else {
$pec_result['error'] = $_POST['email'];
echo json_encode($pec_result);
die();
}
此处的问题是$_POST['email']
的值为NULL
。当emailData
的console.log()返回值时,为什么$ _POST ['email']为null。有人可以帮忙吗?我认为问题在于附加部分。 (不确定)
请不要jQuery 。我知道如何在jQuery中执行此操作,但我想学习如何在javascript中执行此操作。所以,谢谢
答案 0 :(得分:4)
您的问题是,FormData
请求的发送时间为multipart/form-data
而不是application/x-www-form-urlencoded
。删除设置内容类型的行。将FormData
对象传递给XMLHttpRequest.send
时,将自动设置正确的内容类型。
答案 1 :(得分:1)
试试(已编辑)
fd='email='+emailData;
完整代码:
function eAC(emailData) {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
}
if (!httpRequest) {
return false;
}
console.log(emailData);
// var fd = new FormData();
// fd.append("email", emailData);
fd='email='+emailData;
httpRequest.onreadystatechange = eAC_callback;
httpRequest.open('POST', "http://website.com/file.php");
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(fd);
}
function eAC_callback() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log(response);
} else {
return false;
}
}
};