从$ .post回调中返回函数值

JS:

function verificaExistPed(numped){ var valida; jQuery.post("procedures/class_oc.php", // ajax post { cache : false, checkYear : true, numped : numped }, function(data) { if(data === "s"){ valida = true; }else{ valida = false; } } ) return valida; } 

并且,在另一个地方调用该函数,应该在变量check返回valida结果,在我的情况下,返回truefalse

 var check = verificaExistPed('".$numped."'); alert(check); // always undifined 

但是,总是未定义的。

如何从$.post回调中将valida设置为truefalse

你无法返回,因为jQuery.post是一个异步调用。 您必须依赖回调函数才能从服务器获取响应。 试试这个:

  function verificaExistPed(numped, isValidCallback){ jQuery.post("procedures/class_oc.php", // ajax post { cache : false, checkYear : true, numped : numped }, function(data) { isValidCallback(data === "s"); } ) } 

用法:

 verificaExistPed('".$numped."', function(isValid) { alert(isValid); //returns true or false }); 

这是因为在调用functon之后,会异步调用处理程序。 所以你同步请求它,如:

 function test() { var html = $.ajax({ url: "procedures/class_oc.php", async: false // <-- heres the key ! }).responseText; return html; }