0

我创建了一个 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(); 
});
4

3 回答 3

1

由于您要替换输入 #url2,因此 $('#url2').change() 将不起作用。尝试委派它

$('#container_for_url2').delegate('#url2', 'change', function() {
  handleUpload();
});
于 2012-09-22T01:31:45.670 回答
1

线

$('#container_for_url2').html('<input type="file" name="file" id="url2" />');

implies that the element to which the change handler is attached, is overwritten by its own action.

You can overcome this by delegating to the element's container as follows :

$('#container_for_url2').on('change', '#url2', handleUpload);

Note: We use .on() since jQuery 1.7 . .bind(), .live() and .delegate() are now deprecated.

EDIT

... as I now realise you already know because I just read your comment under @suke's answer :)

于 2012-09-22T01:43:04.333 回答
0

Just in case it helps here is the format to using jquery for this. I usually like to keep things simple, but ajax is one of the things I do like jQuery for.

THIS IS THE CODE WITH JQUERY with no plugins needed

//Prepare params
var POSTParamsObject = {
    file : fileInput.files[0],
    session_user_id : session_user_id,
    profile_user_id : profile_user_id
}

//Function for handle upload
function handleUpload() {
    return $.ajax({
        url : 'ajax_upload_image_for_post.php',
        type : 'POST',
        data : POSTParamsObject,
        //dataType : 'json', //Uncomment if you don't use json as your response from server
        beforeSend: function ( xhr ) {
           $('#upload_progress').css('display','block');
        }/*,
        success : function(){//success code},
        error : function(){//error}
        */
   });
}    
//Run ajax call and respond to server response. First argument is the status 200 response, and second argument is to respond to errors 

$('#container_for_url2').on('change', '#url2', function(){

  $.when(handleUpload()).then(function(uploaded){//If request was successful...status 200   
    var links = document.getElementById('uploaded');
    $('#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] + '"/>');  
    }
  },
  function(response){//This is if there is a server error, or the wrong data type is returned
    console.log(response);
  });

});
于 2012-09-22T01:54:19.460 回答