这是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'] 为空。谁能帮忙?我认为概率在附加部分。 (不确定)
请不要使用 jQuery。我知道如何在 jQuery 中执行此操作,但我想学习如何在 javascript 中执行此操作。是的,谢谢
最佳答案
您的问题是,对于 FormData
,请求是作为 multipart/form-data
而不是 application/x-www-form-urlencoded
发送的.删除设置内容类型的行。当您将 FormData
对象传递给 XMLHttpRequest.send
时,将自动设置正确的内容类型。
关于javascript - 未发送 XMLHttpRequest 发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21181113/