开发者

creating var from from ajax response

I need to create a function and create a js var from ajax response Can I do something like this:

f开发者_运维问答unction myFunction() {
  $.ajax({
     type: "POST",
     url: "mypage.php",
     data: "name=John&location=Boston",
     success: function(data){
       var newVar = (data);
     }
  });

  return newVar;
}

and on mypage.php

// db insert
echo mysql_insert_id(); // return ID of the latest insert

I'm not sure if using data is appropriate in this case.


$.ajax({
    type: "POST",
    url: "mypage.php",
    data: "name=John&location=Boston",
    success: function(data){
        // <- I'm asynchronous !!!
        var newVar = (data);
    }
});

// <- I return before you set me!
return newVar;

AJAX request go talk to the server and then call the success method some time later. You can garantuee that success will not run before the request has finished. This means you can not return any data.

Instead you need to pass in a callback and use asynchronous programming.

What you want to do instead is something like this.

function myFunction(callback) {
    $.ajax({
        type: "POST",
        url: "mypage.php",
        data: "name=John&location=Boston",
        success: function(data) {
            callback(data);
        }
    });
}

myFunction(function (data) {
    // do stuff.
}); 

The PHP looks fine.

As an alternative you may prefer to use jQuery's deferred syntax.

function myFunction() {
    return $.ajax({
        type: "POST",
        url: "mypage.php",
        data: "name=John&location=Boston"
    });
}

$.when(myFunction()).then(function(data) {
     // handle data return
     someOtherFunction(data);
}, function(error) { 
     // handle ajax error.
});


  • Closure does not have visibilty to newVar.
  • You cannot return from AJAX function as it is done async.


As another alternative to using when as suggested by Raynos, you can just set async to false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜