我知道如何使用jQuery:
$.ajax({
method: 'POST',
url: 'send-data-to.php',
data: {data:"data"}
})但是如何用纯JS发送通过$_POST访问的数据呢?我之所以问这个问题,是因为我遵循了YouTube教程中的Ajax file upload,但我也希望同时发送更多的数据(我不知道如何使用纯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发送的数据如下所示:
data: {var1:var1,var2:var2,var3:var3}等
发布于 2015-06-15 12:19:46
参见此示例
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);https://stackoverflow.com/questions/30844919
复制相似问题