jQuery ajax 成功回调函数定义 [英] jQuery ajax success callback function definition

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

问题描述

我想使用 jQuery ajax 从服务器检索数据.

I want to use jQuery ajax to retrieve data from a server.

我想将成功回调函数定义放在 .ajax() 块之外,如下所示.那么我是否需要像下面这样声明变量 dataFromServer 以便我能够使用从成功回调返回的数据?

I want to put the success callback function definition outside the .ajax() block like the following. So do I need to declare the variable dataFromServer like the following so that I will be able to use the returned data from the success callback?

我见过大多数人在 .ajax() 块中定义成功回调.那么如果我想在外面定义成功回调,下面的代码是否正确?

I've seen most people define the success callback inside the .ajax() block. So is the following code correct if I want to define the success callback outside?

var dataFromServer;  //declare the variable first

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData(dataFromServer)
    })
}

function handleData(data) {
    alert(data);
    //do some stuff
}

推荐答案

只需使用:

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

success 属性只需要一个函数的引用,并将数据作为参数传递给这个函数.

The success property requires only a reference to a function, and passes the data as parameter to this function.

由于 handleData 的声明方式,您可以像这样访问 handleData 函数.JavaScript 将在运行之前解析您的函数声明代码,因此您将能够在实际声明之前的代码中使用该函数.这称为提升.

You can access your handleData function like this because of the way handleData is declared. JavaScript will parse your code for function declarations before running it, so you'll be able to use the function in code that's before the actual declaration. This is known as hoisting.

尽管如此,这对于这样声明的函数来说不算数:

This doesn't count for functions declared like this, though:

var myfunction = function(){}

这些只有在解释器通过时才可用.

Those are only available when the interpreter passed them.

有关这两种声明方式的更多信息,请参阅此问题功能

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

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