gpt4 book ai didi

javascript - 将变量从 javascript(Ajax) 传递到 PHP

转载 作者:行者123 更新时间:2023-11-30 05:44:13 25 4
gpt4 key购买 nike

我有一个带进度条的文件上传脚本。我做了一些修改以进行一些检查并且一切正常。关于将变量从 javascript(ajax) 文件传递​​到 php 文件有一个小问题

这是我的代码:

var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var folder = 7;
var fileInput = document.getElementById('file');

var data = new FormData();

data.append('ajax', true);
for (var i = 0; i < fileInput.files.length; ++i){
data.append('file[]', fileInput.files[i]);
}

var request = new XMLHttpRequest();

request.upload.addEventListener('progress', function(event){
if(event.lengthComputable){
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');

while (progress.hasChildNodes()){
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) +' %'));
document.getElementById("loading-progress-17").style.width= Math.round(percent * 100) +'%';
}
});
request.upload.addEventListener('load', function(event){
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event){
alert('Upload failed');
});
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if(this.status == 200){
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
for (var i = 0; i < uploaded.length; ++i){
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'files/' + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
}else{
console.log('server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);

}

window.addEventListener('load', function(event){

var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});

发送的形式已经设置好了,但不能很好地修改它,因为没有太多地使用javascript。我尝试做的就是将 var folder = 7; 传递给 upload.php,如这部分代码所示:

request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);

知道如何传递变量吗?

最佳答案

我认为你的代码可能是

data.append('folder', folder);
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);


你在 php 中的变量将是

$_REQUEST['folder']

关于javascript - 将变量从 javascript(Ajax) 传递到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18895735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com