如何利用异步 XMLHttpRequest 的回调函数? [英] How can I take advantage of callback functions for asynchronous XMLHttpRequest?

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

问题描述

我目前正在编写 JavaScript 并且对回调感到困惑.我发现它不是一种内置函数...
我现在正在阅读 O'Relly JavaScript 5th Edition,它显示了如下所示的示例代码:

I'm currently writing JavaScript and confusing about callback. I've found it's not kind of built-in functions though...
I'm now reading O'Relly JavaScript 5th Edition and it shows a sample code something like below:

getText = function(url, callback) // How can I use this callback?
{
    var request = new XMLHttpRequest();
    request.onreadystatechange = function()
    {
        if (request.readyState == 4 && request.status == 200)
        {
            callback(request.responseText); // Another callback here
        }
    }
    request.open('GET', url);
    request.send();
}

基本上,我想我不理解 callback 的一般概念……有人可以编写一个示例代码来利用上面的 callback 吗?>

Basically, I suppose I don't understand the general idea of callback though... Could someone write a sample code to take advantage of callback above?

推荐答案

回调非常简单和漂亮!由于 AJAX 调用的性质,您不要阻止脚本的执行,直到您的请求结束(那时它将是同步的).回调只是一种指定的方法,用于在响应返回到您的方法后对其进行处理.

Callbacks are pretty simple and nifty! Because of the nature of AJAX calls, you don't block execution of your script till your request is over (it would be synchronous then). A callback is simply a method designated to handle the response once it gets back to your method.

由于 javascript 方法是第一类对象,您可以像变量一样传递它们.

Since javascript methods are first class objects, you can pass them around like variables.

所以在你的例子中

getText = function(url, callback) // How can I use this callback?
{
    var request = new XMLHttpRequest();
    request.onreadystatechange = function()
    {
        if (request.readyState == 4 && request.status == 200)
        {
            callback(request.responseText); // Another callback here
        }
    }; 
    request.open('GET', url);
    request.send();
}

function mycallback(data) {
   alert(data);
}

getText('somephpfile.php', mycallback); //passing mycallback as a method

如果您执行上述操作,则意味着您将 mycallback 作为处理响应(回调)的方法传递.

If you do the above, it means you pass mycallback as a method that handles your response (callback).

编辑

虽然这里的例子没有说明回调的正确好处(毕竟你可以简单地将警报放在 onReadyStateChange 函数中!),但可重用性肯定是一个因素.

While the example here doesn't illustrate the proper benefit of a callback (you could simply put the alert in the onReadyStateChange function after all!), re usability is certainly a factor.

你必须记住,这里重要的是 JS 方法是第一类对象.这意味着您可以像对象一样传递它们并将它们附加到各种事件.当事件触发时,会调用附加到这些事件的方法.

You have to keep in mind that the important thing here is that JS methods are first class objects. This means that you can pass them around like objects and attach them to all sorts of events. When events trigger, the methods attached to those events are called.

当您执行 request.onreadystatechange = function(){} 时,您只是在指定要在适当的事件触发时调用的方法.

When you do request.onreadystatechange = function(){} you're just assigning that method to be called when the appropriate event fires.

所以这里很酷的事情是这些方法可以重用.假设您有一个错误处理方法,它会在 AJAX 请求中出现 404 的情况下弹出警报并填充 HTML 页面中的某些字段.

So the cool thing here is that these methods can be reused. Say you have an error handling method that pops up an alert and populates some fields in the HTML page in the case of a 404 in the AJAX request.

如果您无法分配回调或将方法作为参数传递,则必须一遍又一遍地编写错误处理代码,而您只需将其分配为回调和所有错误处理将一口气排序.

If you couldn't assign callbacks or pass methods as parameters, you'd have to write the error handling code over and over again, but instead all you have to do is just assign it as a callback and all your error handling will be sorted in one go.

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

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