如何使用Ajax创建回调函数? [英] How to create callback function using Ajax?

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

问题描述

我正在使用jquery来调用一个函数,以获取在页面刷新时要存储的变量email_number的返回值.

I am working on the jquery to call a function to get the return value that I want to store for the variable email_number when I refresh on a page.

当我尝试此操作时:

function get_emailno(emailid, mailfolder) {

    $.ajax({
        url: 'getemailnumber.php',
        type: 'POST',

        data : {
            emailid: emailid,
            mailfolder: mailfolder
        },

        success: function(data)
        {
            email_number = data;
        }
    });
    return email_number;
}

仅当我在email_number = data;之后使用alert(email_number)时,我将获得作为6的返回值,但是我无法在函数外部获得该值.

I will get the return value as 6 as only when I use alert(email_number) after the email_number = data;, but I am unable to get the value outside of a function.

这是完整的代码:

var email_number = '';

// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
    var hash    = window.location.hash;
    var mailfolder = hash.split('/')[0].replace('#', '');
    var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
    get_emailno(emailid, mailfolder);
}

function get_emailno(emailid, mailfolder) {

    $.ajax({
        url: 'getemailnumber.php',
        type: 'POST',

        data : {
            emailid: emailid,
            mailfolder: mailfolder
        },

        success: function(data)
        {
            email_number = data;
        }
    });
    return email_number;
}

但是,我一直在研究,它表明我需要通过ajax使用回调,但是我不知道如何执行此操作.

However, I have been researching and it stated that I would need to use callback via ajax but I have got no idea how to do this.

我已经尝试过了,但是在get_emailno函数之外我仍然没有得到返回值.

I have tried this and I still don't get a return value outside of the get_emailno function.

    $.ajax({
        url: 'getemailnumber.php',
        type: 'POST',
        async: true,

        data : {
            emailid: emailid,
            mailfolder: mailfolder
        },

        success: function(data)
        {
            email_number = data;
        }
    });

由于无法找到解决方案,我感到沮丧,因此需要您的帮助.我想做的是要调用get_emailno函数以获取返回值以存储在email_number变量中.

I am getting frustrated as I am unable to find the solution so I need your help with this. What I am trying to do is I want to call on a get_emailno function to get the return value to store in the email_number variable.

能否请您举一个示例,说明如何在ajax上使用回调函数以获取返回值,该值可以将值存储在email_number变量中?

Can you please show me an example how I could use a callback function on ajax to get the return value where I can be able to store the value in the email_number variable?

谢谢.

推荐答案

来自 jquery文档$.ajax()方法返回一个jqXHR对象(该对象完全作为jquery XMLHttpRequest对象读取).

From the jquery documentation, the $.ajax() method returns a jqXHR object (this reads fully as jquery XMLHttpRequest object).

当您使用类似这样的其他功能从服务器返回数据时

When you return data from the server in another function like this

function get_emailno(emailid, mailfolder) {

    $.ajax({ 
        // ajax settings
    });
    return email_number;
}

请注意,$.ajax ({...})调用是异步的.因此,其中的代码不一定在最后一个return语句之前执行.换句话说,$.ajax ()调用被延迟 在将来的某个时间执行,而return语句将立即执行.

Note that $.ajax ({...}) call is asynchronous. Hence, the code within it doesn't necessarily execute before the last return statement. In other words, the $.ajax () call is deferred to execute at some time in the future, while the return statement executes immediately.

因此,jquery指定您使用回调和 not 返回语句来处理(或响应)ajax请求的执行.

Consequently, jquery specifies that you handle (or respond to) the execution of ajax requests using callbacks and not return statements.

有两种定义回调的方法.

There are two ways you can define callbacks.

1..在这样的jquery ajax请求设置中定义它们:

1. Define them within the jquery ajax request settings like this:

$.ajax({ 
    // other ajax settings 
    success: function(data) {},
    error: function() {},
    complete: function() {},
});

2.或将回调链接到返回的jqXHR对象,如下所示:

2. Or chain the callbacks to the returned jqXHR object like this:

$.ajax({ 
    // other ajax settings 
}).done(function(data) {}).fail(function() {}).always(function() {});

这两种方法是等效的. success:等同于done()error:等同于fail()complete:等同于always().

The two methods are equivalent. success: is equivalent to done(), error: is equivalent to fail() and complete: is equivalent to always().

何时适合使用哪个函数:使用success:处理返回的数据是您期望的情况;如果在请求期间出现问题,请使用error:,并在请求完成后最终使用complete:(无论请求是否成功).

On when it is appropriate to use which function: use success: to handle the case where the returned data is what you expect; use error: if something went wrong during the request and finally use complete: when the request is finished (regardless of whether it was successful or not).

有了这些知识,您可以更好地编写代码以捕获在正确的时间 从服务器返回的数据.

With this knowledge, you can better write your code to catch the data returned from the server at the right time.

var email_number = '';

// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
    var hash    = window.location.hash;
    var mailfolder = hash.split('/')[0].replace('#', '');
    var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
    get_emailno(emailid, mailfolder);
}

function get_emailno(emailid, mailfolder) {

    $.ajax({
        url: 'getemailnumber.php',
        type: 'POST',

        data : {
            emailid: emailid,
            mailfolder: mailfolder
        },

        success: function(data)
        {
            // sufficient to get returned data
            email_number = data;

            // use email_number here
            alert(email_number); // alert it
            console.log(email_number); // or log it
            $('body').html(email_number); // or append to DOM
        }
    });
}

这篇关于如何使用Ajax创建回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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