ajax return true/false-我已经实现了一个回调 [英] ajax return true/false - I have implemented a callback

查看:116
本文介绍了ajax return true/false-我已经实现了一个回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我已阅读本主题在回调函数中为jQuery的ajax数据参数返回什么?

First of all I have read this topics jQuery AJAX function return true or false returning only false while its all good, What to return for jQuery's ajax data param in callback function?, How return true or false function of data response ajax? and I can't figure out how to put this working.

$("#btn_go").on('click', function(){
    if(validateUserDetails() == false){ 
            return;
    }
});

因此,函数validateUserDetails具有以下内容:

So, the function validateUserDetails has the following:

function validateUserDetails(){
    var bool = false;

    $.ajax({
        url: 'response.php?type=validateUserDetails',
        type: 'POST',
        dataType: 'json',
        data: {name: $("#checkout_name").val(), email: $("#checkout_email").val(), "country": $("#checkout_country").val(), 
               "city": $("#checkout_city").val()},
        success: function(data){
            console.log(data); // this is currently returning FALSE
                               // Which is totally correct!
            if(data == true){ bool = true; }
            return trueOrFalse(bool);
        }
    });
}

function trueOrFalse(bool){
    return bool;
}

但是这不起作用,因为如果我输出该函数,则会得到未定义",这意味着该函数未在重新调整正确的值. console.log(validateUserDetails()); // = undefined

But this is not working because if I output the function I get "undefined", which means that the function is not retuning the correct value. console.log(validateUserDetails()); // = undefined

我在做什么?

推荐答案

ajax请求为asynchronous.不要使用sync: true选项,这不是一个好主意. 您可以做的是使用ajax返回的promise,因此:

ajax request is asynchronous. Don't use the sync: true option, it's not really a good idea. What you can do is to use the promise that the ajax returns, so:

function validateUserDetails(){

return $.ajax({
    url: 'response.php?type=validateUserDetails',
    type: 'POST',
    async: false,
    dataType: 'json',
    data: {name: $("#checkout_name").val(), email: $("#checkout_email").val(), "country": $("#checkout_country").val(), 
           "city": $("#checkout_city").val()},
    success: function(data){
        console.log(data); // this is currently returning FALSE
    }
  });
}
$("#btn_go").on('click', function(){
    validateUserDetails().done(function(data){
         if(data == "someValue")
            return "whatever you want";
    });
});

这篇关于ajax return true/false-我已经实现了一个回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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