我如何用js函数回调 [英] how do i callback with js function

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

问题描述

我在使用回调时遇到了麻烦,主要是因为我不了解它们是如何工作的(或应该工作的).

I'm having trouble with callbacks mainly because I don't understand how they're working (or supposed to work).

我有我的职能

function checkDuplicateIndex(values, callback) {
    $.ajax({
        type: "POST", 
        url: url, 
        data: "command=checkIndexAlbumTracks&" + values,
        dataType: "html",
        success: function(data){
            var returnValue = data.d;   
            callback(returnValue);
        }
    });
}

然后在Submit事件中,如何正确调用checkDuplicateIndex,以便我可以alert()值?

And then within a submit event, how do I properly call checkDuplicateIndex so that I can alert() the value?

推荐答案

这最终是一个很长的答案,所以我将尝试将其拆分为多个部分.

This ended up being a long answer, so I'm going to try to split it into pieces.

因此在javascript中,函数是一个可以传递,分配给变量等的对象,就像其他任何数据类型一样.区别在于,函数而不是文本,数字等的字符串,而是等待执行的代码块.

So within javascript, a function is an object that can be passed around, assigned to a variable, etc, just like any other data type. The difference is that a function, rather than being a string of text, number, etc, is a block of code waiting to be executed.

这通常会使刚开始编程的人感到困惑,因为通常在您编写代码时,它是在运行程序时执行的.但是对于功能而言,并非如此.当您在函数内部编写代码时,它会等到您调用该函数之后再执行.如果不调用该函数,则永远不会执行该代码.让我们来看一个简单的例子:

This is often confusing to people starting out with programming because usually when you write code, it is executed when you run the program. But for functions, this is not the case. When you write code inside a function, it waits there not executing until you call the function. If you do not call the function, the code is never executed. Let's check out a quick example:

function say_hello(){
  console.log('hello!');
}

您在此处看到的称为功能声明.这意味着您正在创建一个函数,该函数是等待执行的代码块.如果运行此代码,则不会将任何内容记录到控制台.现在,让我们来看一个函数 call .

What you see here is called a function declaration. This means you are creating a function, which is a block of code waiting to be executed. If you run this code, nothing will be logged to the console. Now let's look at a function call.

function say_hello(){
  console.log('hello!');
}

say_hello();

因此,在这里我们像以前一样声明该函数,但是在下面我们对其进行调用.函数调用只是函数名称,后跟打开和关闭括号.如果该函数接受参数,则它们将位于内部,但现在无需担心.如果要运行此代码,实际上您会看到hello!记录到控制台,因为调用了该函数,该函数将在内部执行代码.

So here we declare the function just like before, but below we call it. A function call is just the name of the function followed by open and close parens. If the function takes arguments, they will be inside the parens, but no need to worry about that for now. If you were to run this code, you would in fact see hello! logged to the console, because the function was called, which executes the code inside.

现在,让我们切换一下齿轮.当您进行jquery ajax调用时,jquery将许多代码抽象到库中.他们负责设置XMLHttpRequest,将其发射到您指定的位置,然后收集结果,并以跨浏览器工作的方式进行操作.但是由于javascript是异步,因此ajax调用一旦结束,javascript就会在ajax调用之后继续执行代码,因为谁愿意等待别人的服务器响应,而您可能仍然开始从事这项工作.因此,如果您触发类似这样的内容:

Now, let's switch gears for a second. When you make a jquery ajax call, jquery abstracts a lot of code into the library. They take care of setting up the XMLHttpRequest, firing it off to the place you specify, and collecting the result, and they do this in a way that works cross-browser. But since javascript is asynchronous, as soon as the ajax call goes off, javascript keeps executing code after the ajax call, because who wants to wait around for someone else's server to respond while you could be still getting in that work. So if you fire off something like this:

$.ajax({
  url: 'http://google.com',
  success: function(){ console.log('done!') }
});

console.log('after ajax call');

...您可能会惊讶地发现它记录after ajax call 之前记录done!.如前所述,这是因为在JavaScript调用中,与I/O的交易通常是异步的.

...you may be surprised to find that it logs after ajax call before logging done!. This is because, as stated earlier, in javascript calls that deal with I/O are often asynchronous.

因此,如果进行了ajax调用并且即使ajax调用尚未完成,它也会立即继续执行代码,我们如何指定完成后将运行的代码?这是所有事物融合在一起的地方.通过为jquery提供一个函数(我们记得这是一个未执行的代码块),我们可以为自己提供一种方法,使我们自己编写代码,该代码仅在ajax调用完成后后执行,方法是传递未执行的代码传递给jquery,并大声地说:嘿,jquery,接受此代码,当ajax调用完成时,调用它并传入您从其中获得的任何数据."多么方便!

So if the ajax call is made and it immediately continues executing code even if the ajax call has not finished, how can we specify code that will run when it's finished? This is where everything comes together. By providing jquery with a function, which as we remember is a block of unexecuted code, we can provide a way for ourselves to write code that is executed only after the ajax call has finished by passing the block of unexecuted code to jquery and saying essetially "hey jquery, take this code, and when the ajax call is finished, call it and pass in any data you got out of it." How convenient!

我们这样做的方法是通过 jquery的ajax函数.如果请求成功,它将调用我们传递给success的函数,我假设您可以猜测如果发生错误会发生什么情况.

The way we do this is through the success and error properites of jquery's ajax function. If the request was successful, it will call the function we pass to success, and I assume you can guess what happens if there was an error.

异步代码和一流的功能是有关javascript的两个最令人困惑的部分,一旦您理解了这两个概念,您将处在一个不错的位置,尽管可能要花一些时间才能到达那里.因此,仔细考虑并进行实验非常重要.让我们通过几种方式来处理有关jquery ajax的示例.

Asynchronous code and first class functions are two of the most confusing parts about javascript, and once you understand these two concepts, you'll be in a great spot, although it may take a while to get there. So it's important to think carefully about it and experiment. Let's talk through a couple ways to handle the example you are working with here, about jquery ajax.

首先,我们可以尝试制作自己的函数并将该函数的名称传递给成功处理程序.然后,当它返回时,将调用该函数.让我们看一下:

First, we can try making our own function and passing the name of the function to the success handler. Then when it comes back, it will call the function. Let's take a look:

var my_callback = function(data){
  console.log(data);
}

$.ajax({
  url: 'http://google.com',
  success: my_callback
});

这是一种有趣的方式.在这里,我们为变量分配了匿名函数,然后将变量名称传递给成功处理程序.这样就可以了.现在让我们尝试另一种方式:

This is an interesting way of doing it. Here we have assigned an anonymous function to a variable, then passed the variable name to the success handler. This will work fine. Now let's try another way:

function my_callback(data){
  console.log(data);
}

$.ajax({
  url: 'http://google.com',
  success: my_callback
});

在这里,我们定义一个命名函数并执行相同的操作.这将以相同的方式工作. javascript中的命名函数实际上可以在使用后声明,因此您可以将函数声明移至ajax调用下方,并且仍然可以使用.试试看这是命名函数的一个很好的优势.

Here, we define a named function and do the same thing. This will work the same way. Named functions in javascript can actually be declared after the are used, so you could move the function declaration below the ajax call and it would still work. Try this out. This is a nice advantage to named functions.

最后,让我们看一下处理它的第三种方式:

Finally, let's take a look at a third way we could handle it:

$.ajax({
  url: 'http://google.com',
  success: function(data){
    console.log(data);
  }
});

在这里,我们在成功处理程序上内联定义一个匿名函数.这与其他两个选项中的任何一个完全相同.通过这三种方式,jquery都会接收一个函数声明,并在需要时调用它,即ajax请求返回之后.

Here, we define an anonymous function right inline on the success handler. This works exactly the same as either of the other two options. In all three of these ways, jquery receives a function declaration, and calls it when it needs to, which is after the ajax request has come back.

我知道这是一个 super 的长答案,但是您对此感到困惑的是javascript的一些核心概念,我认为在这里复习它们会比在javascript中更有用.只是解决您的问题并给您答案,而无需对概念进行解释.实际上,我实际上并没有解决您的问题,但是您在理解这些概念后将可以轻松地自己解决问题.如果您仍然遇到问题,请发表评论,我会尽力澄清更多.

I know this is a super long answer, but what you are confused about here are some of the core concepts of javascript, and I thought it would be more helpful to go over them here than to just solve your problem and give you the answer without explanation of the concepts. In fact, I haven't actually tackled your problem here at all, but you will easily be able to solve it yourself after understanding these concepts. If you are still having trouble, drop a comment and I'll try to clarify more.

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

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