使用Ajax的JavaScript代码中的评估顺序? [英] Order of evaluation in JavaScript code using Ajax?

查看:169
本文介绍了使用Ajax的JavaScript代码中的评估顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎(对我来说)像javascript语句不总是一个接一个地运行。我知道他们这样做,但有时看起来像一个show()函数同时触发与hide(),所以逻辑失败。有要使用的回调函数,如jQuery.load(some.html,thenrunthis)..



我需要理解工作逻辑。



thx。

解决方案

真的要问一下 AJAX 中的A。它代表异步,它允许您在没有阻止的情况下发出请求。如果/请求成功时,回调函数将被执行,但其余代码将继续执行。这种方法的主要优点之一是UI响应性。同步调用基本上会冻结浏览器,直到您的请求返回,这可能需要一段时间。



修改答案,我想我会指出,回调函数不限于AJAX请求。由于您似乎使用jQuery,因此您可能需要查看 jQuery Events API 了解更多使用

假设您希望在文本输入字段获取焦点时以特定方式响应。 下面是一个直接来自 jQuery文档的示例,其中回调函数用于响应到输入元素获取焦点:

  $(input) .focus(function(){
$(this).next(span)css('display','inline')。fadeOut(1000);
});

这个函数真的是一个回调函数。当用户在页面上选择输入元素时,将调用它。上述代码的操作演示此处


It seems (to me) like javascript statements do not always run one after another. I know they do that way but sometimes it seems like a show() func tion fires at the same time with hide() so the logic fails. There are callback functions to use, like jQuery.load("some.html",thenrunthis) ..

I need to understand the working logic. any help/leads?

thx in advance

解决方案

You are really asking about the "A" in AJAX. It stands for asynchronous, and it allows you to make a request without blocking. The callback function will be executed if/when the request succeeds, but the rest of your code will continue to execute. One of the main advantages to this approach is UI responsiveness. A synchronous call will essentially freeze the browser until your request returns, which could take a while.

Edit: To expand a little on my original answer, I thought I'd point out that callback functions are not limited to AJAX requests. Since you seem to be using jQuery, you might want to look at the jQuery Events API for more examples using callbacks.

Example: Suppose you want to respond a certain way when a text input field gets focus. Here is an example straight from the jQuery documentation in which a callback function is used to respond to an input element obtains focus:

$("input").focus(function () {
     $(this).next("span").css('display','inline').fadeOut(1000);
});

That function is really a callback function. It will be called when the user selects an input element on the page. There is a working demonstration of the above code in action here.

这篇关于使用Ajax的JavaScript代码中的评估顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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