Upload an image on ajax to get the image path

var formData = new FormData ();
formData.append ("image", document.getElementById ("FileUpload"). Files [0]);
$.ajax ({

)
url: url,
type: "post",
data: formData,
cache: false,
/**
*falseContent-Type
*/
contentType: false,
/**
* falsejQuery formdata 
* XMLHttpRequest formdata 
*/
processData: false,
success: function (data) {
    console.log(data)
    if (data.code == "200") {
        this.imageUrl = data.data
    }
}

})
cannot get the path outside ajax, so this.imageUrl ="
appears. Why? Who has encountered similar problems?

Mar.28,2021

you can define a global variable and assign the acquired path to the global variable


ajax with a delay, but of course you can't get it outside.


Ajax is asynchronous

    if (data.code == '200') {
        this.imageUrl = data.data
    }
    

the this here has pointed to the callback function that does not work externally
you can change it to:

var imageUrl = '';
//Js

$.ajax({//......
    if (data.code == '200') {
        imageUrl = data.data
        console.log(imageUrl); // 'https://img.codeshelper.com/upload/img/2021/03/27/uy5sto4o2me13502.jpg'
    }
   
//...
console.log(imageUrl); // ''
//    
// ajax
Menu