从函数ajax返回 [英] return from a function ajax

查看:132
本文介绍了从函数ajax返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有数据验证,我在这里遇到问题。更多的函数$ ajax jquery不返回true和false的值,知道如何解决这个问题吗?

I am having a problem here, if I have a data verification. More of the function $ ajax jquery not return value of true and false, know how I can fix this?

function ret(as){
    ....codes...
     $.ajax({
        type: "POST",
        url: "../../03",
        data: "as="+as,
        success: function (msg) {
          if(msg == 'true' ){
           ..codes..
           return true;  
          }else{
           ..codes..
           return false;
          }
        } 
    });
  }

示例电话:

var check= ret("user");

if(check== true){
  ..run ..
}


推荐答案

默认情况下,ajax调用是异步的 - 实际上是'A'代表的。这意味着你的ret函数将在调用success函数之前返回。您有两种方法可以解决您的问题:

By default ajax calls are asynchronous - that's actually what the 'A' stands for. This means that the your ret function will return before the success function is ever invoked. You have two options for fixing your issue:


  1. 使您的ajax调用同步 - 请参阅 http://api.jquery.com/jQuery.ajax/ 。这几乎总是一个坏主意,因为整个页面将阻塞,直到调用返回

  2. 反转您的控制流,以便在调用成功回调时发生所需的行为。您可以通过将函数传递给ret来执行此操作:

  1. Make your ajax call synchronous - see the async options at http://api.jquery.com/jQuery.ajax/. This is almost always a bad idea, because the entire page will block until the call returns
  2. Invert your control flow so that the desired behavior happens when the success callback is invoked. You can do this by passing a function into ret:

函数(as,successHandler){
...

function(as, successHandler) { ...

success: function(msg) {
    successHandler(msg == 'true');
}


这篇关于从函数ajax返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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