jQuery的阿贾克斯成功的回调函数定义 [英] jQuery ajax success callback function definition

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

问题描述

我想使用jQuery AJAX从服务器获取数据。

我想把阿贾克斯()阻止类似下面以外的成功回调函数的定义。所以,我需要声明变量 dataFromServer 像下面这样我就可以从成功的回调使用返回的数据?

我见过的大多数人定义在阿贾克斯()块的成功回调。那么,下面的code正确的,如果我想外界定义成功的回调?

  VAR dataFromServer; //首先声明变量

功能的getData(){
    $阿贾克斯({
        网址:'example.com',
        键入:GET,
        成功:handleData(dataFromServer)
    })
}

函数handleData(数据){
    警报(数据);
    //做一些东西
}
 

解决方案

只需使用:

 函数的getData(){
    $阿贾克斯({
        网址:'example.com',
        键入:GET,
        成功:handleData
    })
}
 

成功属性只需要引用的函数,并传递数据作为参数传递给这个函数。

您可以访问,因为 handleData 声明的方式这样你的 handleData 功能。用JavaScript解析您的code的函数声明运行前,这样你就可以使用code中的函数,是实际的声明之前。这就是所谓的提升

这不计算为这样的声明的函数,虽然:

  VAR的MyFunction =功能(){}
 

这些都是只有在间preTER通过它们可用。

<一个href="http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname">See这个问题有关的2种方式宣告功能

了解更多信息

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

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?

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
}

解决方案

Just use:

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

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

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.

See this question for more information about the 2 ways of declaring functions

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

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