How to return the value of a function after the result of an ajax call has come?

后端 未结 3 1044
鱼传尺愫
鱼传尺愫 2020-12-21 04:05

Sort of like this:

function getfoo() {
  var foo = \"\";
  $.get(\"foofile.html\", function (data) {
    foo = data;
  });
  return foo;
}

3条回答
  •  温柔的废话
    2020-12-21 04:51

    You should use a callback pass to the function and let it deal your data.

    function getfoo(callback) {
      var foo = "";
      $.get("foofile.html", function (data) {
        callback(data);
        // do some other things
        // ...
      });
    }
    
    getfoo(function(data) {
       console.log(data);
    });
    

提交回复
热议问题