使用纯JS(Ajax)将数据发送到PHP文件

时间:2015-06-15 12:14:02

标签: javascript php ajax

我知道如何使用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}

1 个答案:

答案 0 :(得分:1)

参见此示例

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);

来自Send POST data using XMLHttpRequest