Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

javascript - How to return data from ajax success function?

In my front end JavaScript application, I make an ajax request to fetch data from the server. As soon as I get the data, I want to return that piece of information to the view.

var view_data;
$.ajax({
    url:"/getDataFromServer.json",
    //async: false,
    type: "POST",
    dataType: "json",
    success:function(response_data_json) {
        view_data = response_data_json.view_data;
        console.log(view_data); //Shows the correct piece of information
        return view_data; // Does not work. Returns empty data
    }
 });

 // return view_data; --> Keeping the return outside of the ajax call works but then I need to make my ajax call synchronous in order for this return clause to be executed after the ajax call fetches data.

How would I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of returning data from success: pass data to a function.

var view_data;
$.ajax({
    url:"/getDataFromServer.json",
    //async: false,
    type: "POST",
    dataType: "json",
    success:function(response_data_json) {
        view_data = response_data_json.view_data;
        console.log(view_data); //Shows the correct piece of information
        doWork(view_data); // Pass data to a function
    }
 });

function doWork(data)
{
    //perform work here
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...