Sil*_*ght 0 javascript ajax jquery
我想写一个javascript函数,它将向PHP脚本发出ajax请求并返回它的结果.这就是它的样子:
function myjsfunc(some_data)
{
$.post(
"/myscript.php",
{ some_data: some_data },
function(response)
{
result = response;
}
);
return result;
}
Run Code Online (Sandbox Code Playgroud)
问题是,这result总是未定义的.这可能是因为变量result不在myjsfunc命名空间中?或者是因为在处理主函数后接收到成功函数结果?
无论如何,我怎样才能获得理想的结果?有办法吗?
您无法返回结果,因为它不是由外部函数完成时定义的.您的AJAX调用是异步发生的,并且在POST发生后调用回调函数.要处理结果,您需要执行以下操作:
function myjsfunc(some_data) {
$.post("/myscript.php", { some_data: some_data }, function(response) {
if (some_data.prop) {
myReturnHandler(response);
} else {
myOtherHandler(response);
}
}
);
}
Run Code Online (Sandbox Code Playgroud)
您将分别定义myReturnHandler,并且需要知道如何使用结果数据接管处理.
- 已编辑 -
您还可以执行测试以确定如何处理响应.添加了额外的代码来演示.
| 归档时间: |
|
| 查看次数: |
3126 次 |
| 最近记录: |