返回jQuery Ajax发布

I wish to use the jQuery.post class to return (not alert) the response within a function.

The following gives an alert with the appropriate value:

function test_func() {
    $.post("test.php", { cmd: "testing" }, function (data) { alert(data); })
}

(displays alert with appropriate value)

I tried the following:

function test_func() {
    return $.post("test.php", { cmd: "testing" }, function (data) { return data; })
}

(returned object)

function test_func() {
    var tmp;
    $.post("test.php", { cmd: "testing" }, function (data) { tmp=data; })
    return tmp;
}

(returned undefined)

var tmp;

function setTmp(n) {
    tmp=n;
}

function test_func() {
    t=$.post("test.php", { cmd: "testing" }, function (data) { setTmp(data); })
}

(returned undefined)

function test_func() {
    t=$.post("test.php", { cmd: "testing" })
    return t.responseText;
}

(returned undefined)

So what's the deal? How can I make "test_func()" return the data response text?

Being an asynchronous request, you aren't able to get a response as soon as you call the function. Instead, the function that you pass to $.post is intended to be a callback that will perform some action as soon as the response is complete. Consider the following:

function myCallback(response) {
  // do something with `response`...
}

function test_func() {
  $.post("test.php", { cmd: "testing" }, myCallback)
}

Instead of directly returning a response, you can instead manipulate it as needed in the myCallback function.

The deal is ajax is asynchronous one possible solution is to set it as sync like

$.ajaxSetup({
async:false
});

and then

function test_func() {
var temp;
    t=$.post("test.php", { cmd: "testing" })
    return t.responseText;
}

the answer is only to make your current setup work else there are better ways to deal with it