如何使用JavaScript和Ajax发送文件和输入字段来发送php脚本

时间:2015-05-27 10:44:09

标签: javascript php ajax

请有人告诉我如何使用javascript执行此操作。因为我使用javascript和ajax来加载将执行上传的页面,然后使用javascript和ajax将表单提交到php脚本

function AddMultipleContact(){
    var xmlhttp;
  if(window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
var url = "url.php";
var group = document.getElementById("select-input").value;
var file = document.getElementById('file-name').files;
var variables = "select-input="+group+"&file-name="+file;

xmlhttp.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

// Access the onreadystatechange event for the XMLHttpRequest object
xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var data = xmlhttp.responseText;
        document.getElementById("flash-message").innerHTML = data;
    }
}
xmlhttp.send(variables); // Actually execute the request

}

1 个答案:

答案 0 :(得分:1)

文件通常是数据,如二进制或任何东西,它不能只作为查询字符串发送并连接成字符串。

要使用ajax上传文件,您必须使用FormData object,仅支持IE10及更高版本,对于较旧的浏览器,无法上传ajax,并且必须实现iframe等的解决方法

function AddMultipleContact() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var url      = "url.php";
    var group    = document.getElementById("select-input").value;
    var files    = document.getElementById('file-name').files;
    var formData = new FormData();

    for (var i = 0; i < files.length; i++) {
        var file = files[i];

        formData.append('files[]', file, file.name);
    }    

    formData.append('select_input', group);

    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var data = xmlhttp.responseText;
            document.getElementById("flash-message").innerHTML = data;
        }
    }
    xmlhttp.send(formData);
}