如何在ajax调用中返回值? [英] How to return value in ajax call?

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

问题描述

我想在输入keyup之后,如果数据为0,则返回false;如果不是,则返回true.但在我的尝试中,万一data === 0:

I want after keyup in input if data was 0 return is false if was not false return is true. but in my try always return is true in case data === 0:

$('input').live('keyup change', function () {
    var result = true;
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: 'search_customer',
        data: dataObj,
        cache: false,
        success: function (data) {
            if (data == 0) {
                alert('data is 0')
                result = false;
            } else {
                alert('data is not 0')
            }
        }
    })
    //alert(result) this output  always is 'true'
    return result;
})

推荐答案

.ajax()调用在将来的任意时间返回. keyupchange处理程序立即(基本上)返回.

The .ajax() call returns at an arbitrary time in the future. The keyup and change handlers return (essentially) immediately.

success处理程序中进行工作.另外,您可以将全局值(或命名空间全局值)设置为返回的值,但要理解,直到Ajax调用完成,该值才是无效的.

Do the work in your success handler. Alternatively, you could set a global (or namespaced global) to the returned value, with the understanding that it would be invalid until the Ajax call completes.

如果if语句本身未达到您的期望,则还需要确保返回的数据符合您的期望.这与事件处理程序的返回值不同.

You also need to make sure the data being returned is what you expect it to be, if the if statement itself isn't doing what you expect. That's a different issue than the return value from the event handler.

这篇关于如何在ajax调用中返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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