我创建了一个 ajax 函数,用于预览上传的图像并将其保存到文件夹中。问题是ajax 只被调用一次。如果我选择的文件不是图像,则会返回一个字符串,并插入一个新的输入文件 html 来替换旧的文件输入字段。我对XHR不熟悉,只是对它有一个基本的了解。我的问题是,是否可以调用此 ajax 两次,如果可以,如何调用。目前 Firebug 只接收一个 aja 调用。之后,无论我选择什么文件,都没有任何反应。
var handleUpload = function (event) {
var fileInput = document.getElementById('url2');
var session_user_id = <?php echo $session_user_id; ?>;
var profile_user_id = <?php echo $user_id; ?>
var data = new FormData();
data.append('ajax', true);
data.append('file', fileInput.files[0]);
data.append('session_user_id', session_user_id);
data.append('profile_user_id', profile_user_id);
var request = new XMLHttpRequest();
request.upload.addEventListener('load',function(event) {
$('#upload_progress').css('display', 'none');
});
request.upload.addEventListener('error', function(event) {
$('#uploaded').html('Upload Failed!');
});
//code below is part of callback of ajax
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if (this.status == 200) {
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
$('#uploaded').empty();
if (uploaded[0] == 1 || uploaded[0] == 2 || uploaded[0] == 3) {
$('#uploaded').html('Some error occured!');
$('#container_for_url2').html('<input type="file" name="file" id="url2" />');
} else {
$('.preview_image_box2').html('<img width="' + uploaded[1] + '" height="' + uploaded[2] +'" style="position:relative;top:'+ uploaded[3]+'" src="' + uploaded[0] + '"/>');
}
}
} else {console.log('server replied with' + this.status)}
});
request.open('POST', 'ajax_upload_image_for_post.php');
request.setRequestHeader('Cache-Control', 'no-cache');
$('#upload_progress').css('display','block');
request.send(data);
};
url2
在这里,当输入文件字段中插入了文件时,我正在设置 ajax 调用。我怀疑这是问题所在。
$('#url2').change(function () {
handleUpload();
});