我知道如何使用 jQuery:
$.ajax({
method: 'POST',
url: 'send-data-to.php',
data: {data:"data"}
})
但是如何使用纯 JS 发送可通过 $_POST
访问的数据呢?我问这个问题的原因是因为我按照 YouTube 教程进行 Ajax 文件上传
,但我也想随之发送更多数据(而且我不知道如何使用纯JS)。
这是它的主要部分。
JS
function uploadFile(e) {
e.preventDefault();
var file = document.getElementById('upload-btn').files[0];
var formdata = new FormData();
formdata.append("file1",file);
ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress",progressHandler,false);
ajax.addEventListener("load",completeHandler,false);
ajax.addEventListener("error",errorHandler,false);
ajax.addEventListener("abort",abortHandler,false);
ajax.open("POST","upload_file.php");
ajax.send(formdata);
}
HTML
<form method="post" enctype="multipart/form-data" onsubmit="uploadFile(event);">
<input class="next-btn" type="submit" value="Upload!">
<input type="file" name="file1" id="upload-btn" onchange="showImage(this);">
</form>
我想要发送的数据就像使用 jQuery 一样:
数据:{var1:var1,var2:var2,var3:var3}
等
最佳答案
查看此示例
var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
关于javascript - 使用纯JS(Ajax)将数据发送到PHP文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30844919/