在JavaScript函数中使用$ .post,不能为变量赋值吗? [英] Using $.post within a javascript function, cannot assign value to a variable?

查看:143
本文介绍了在JavaScript函数中使用$ .post,不能为变量赋值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在函数中使用$ .post,获取结果,然后根据$ .post回调的结果返回函数true或false.但是,在父函数的返回事件之后,似乎发生了回调.

I'm trying to use $.post within a function, get the results, then return the function true or false based on the results of the $.post callback. However, the callback seems to occur, AFTER the return event of the parent function.

这是当前代码,ret变量始终是未定义的,但是如果我在$ .post回调中将其警报(),它将返回正确的结果;

Here's the current code the ret variable is always undefined but if I alert() it within the $.post callback, it returns the correct result;

function elementExists(key, type, path, appid, pid){
    var ret;
    $.post('?do=elExists', {key: key, type: type, path: path, appid: appid, pid: pid},function(data){
        ret = data;                         
    });

    alert(ret);
    return ret;

}

推荐答案

正如您所发现的,帖子是异步完成的.如果要使其同步,则需要使用 ajax 方法并将async参数设置为false.但是,最好承认该帖子是异步的并构建您的代码,以使回调执行的操作独立于调用该帖子的方法.显然,您确实想要执行警报以外的其他操作,但是却不知道很难建议您如何重构它.

As you've discovered the post is done asynchronously. If you want it to be synchronous, you'll need to use the ajax method and set the async parameter to false. It would be better, however, to acknowledge that the post is asynchronous and build your code so that the action performed by the callback is independent of the method that invokes the post. Obviously, you really want to do something other than the alert, but without knowing what it's hard to advise you how to refactor this.

编辑:据我了解,您的代码正在检查是否存在某些东西,但是出于某种目的正在检查它.如果我们知道目的是什么,那么就有可能在回调中建议如何完成此操作,以便可以重构该方法.

EDIT: I understand that your code is checking to see if something exists, but it is checking that for a purpose. If we knew what the purpose was, then it might be possible to recommend how to accomplish that in the callback so that the method could be refactored.

这篇关于在JavaScript函数中使用$ .post,不能为变量赋值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆