XMLHttpRequest.send返回undefined

时间:2016-06-10 11:49:06

标签: javascript

大家好我的问题是upload()每次都会返回undefined,但我期待是真是假。请指正!并教我在哪里做错了。 uploadToS3是另一个我在S3上调用上传图片的功能。

if(upload("fileFieldId","hiddenTextFieldId","docType","uploadId")){
    alert("success");
}
else{
    alert("upload fail");
}

function upload(fileFieldId,hiddenTextFieldId,docType,uploadId){
    document.getElementById(uploadId).innerHTML = "<b>Uploading ...</b>";
    var dt= new Date();
    var file = document.getElementById(fileFieldId).files[0];
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari   Tue, 07 Jun 2016 14:40:00 GMT
        xmlhttp=new XMLHttpRequest();
    }
    else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    // alert(file.name);
    xmlhttp.open("POST", "/sellerprofile/uploadajax/");
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            var result = JSON.parse(xmlhttp.responseText);
            let headers = {
                'Accept': '*/*',
                'Content-Type': file.type, // or where ever your file object is.
                'Authorization': result.signature, // which you receive from your server
                'x-amz-acl' : 'private', // required
                'x-amz-date' : dt.toUTCString() // required
            }
            let putURL = result.url;
            let nm = result.fileName;
            // alert(result.fileName);
            let uploader = uploadToS3(putURL, headers, file)

            uploader.upload()
            .then((result) => {
                document.getElementById(hiddenTextFieldId).value = nm;
                document.getElementById(uploadId).innerHTML = "<b>File Uploaded</b>";
                document.getElementById(uploadId).style.color = "green";
                document.getElementById(fileFieldId).value = "";
                document.getElementById(fileFieldId).required = false; 
                return true;
            })
            .catch((err) => {
                document.getElementById(uploadId).innerHTML = "<b>Uploading failed....</b>";
                document.getElementById(uploadId).style.color = "red";
                return false;
            })
        }
        else{
            return false;
        }
    }
    var data =  {"type": file.type , "time": dt.toUTCString(), "extention" : (file.name).split('.').pop(),"docType": docType}
    xmlhttp.setRequestHeader("Content-Type", "application/json");
    xmlhttp.send(JSON.stringify(data));
}

2 个答案:

答案 0 :(得分:1)

您应该使用回调或承诺来完成这项工作。我更喜欢回调解决方案。

upload("fileFieldId", "hiddenTextFieldId", "docType", "uploadId", function (status) {
    if (status) {
        alert("success");
    }
    else{
        alert("upload fail");
    }
});

然后上传函数应支持最后一个参数作为回调:

function upload(fileFieldId,hiddenTextFieldId,docType,uploadId, callback) {
    ......
        uploader.upload()
        .then((result) => {
            document.getElementById(hiddenTextFieldId).value = nm;
            document.getElementById(uploadId).innerHTML = "<b>File Uploaded</b>";
            document.getElementById(uploadId).style.color = "green";
            document.getElementById(fileFieldId).value = "";
            document.getElementById(fileFieldId).required = false; 
            callback(true);
        })
        .catch((err) => {
            document.getElementById(uploadId).innerHTML = "<b>Uploading failed....</b>";
            document.getElementById(uploadId).style.color = "red";
            callback(false);
        })
    ......
}

答案 1 :(得分:0)

您正在进行异步的AJAX请求调用,并且在默认流程中,您的函数将不返回任何内容。每个return语句都在onreadystatechange()方法中。因此,如果你调用你的方法,它将发出AJAX请求并立即退出,返回&#39; undefined&#39;因为这里没有退货声明:

var data =  {"type": file.type , "time": dt.toUTCString(), "extention" : (file.name).split('.').pop(),"docType": docType}
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(data));

您可以返回类似标志值的内容,以确定调用是否已成功发送到服务器,如下所示:

return 'CALL_SENT';

并检查返回的值,如:

var valReturned = upload("fileFieldId","hiddenTextFieldId","docType","uploadId");
if(valReturned === 'CALL_SENT'){
    alert("Call sent to the server");
}
else if(valReturned === true){
    alert("succcess");
}
else{
    alert("upload fail");
}

希望这有帮助。