Javascript 什么是 AJAX,它是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6009206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:52:00  来源:igfitidea点击:

What is AJAX and how does it work?

javascriptjqueryajax

提问by onteria_

Possible Duplicate:
How does AJAX work?

可能的重复:
AJAX 是如何工作的?

Note: This is a community wiki post

注意:这是一个社区维基帖子

I've often heard of AJAX being used for providing a user with dynamic content. What is it and how does it work?

我经常听说 AJAX 用于为用户提供动态内容。它是什么以及它是如何工作的?

回答by onteria_

AJAX, or (A)synchronous (J)avascript (A)nd (X)ML (which interestingly enough tends to use JSON more these days), is a system in which Javascript uses a browser object to communicate with a remote server. The general use case of this is to be able to update a client's interface without needing to go to another page. Before we begin though, a few words of caution.

AJAX,或 (A)synchronous (J)avascript (A)nd (X)ML(有趣的是,这些天更倾向于使用 JSON)是一种系统,其中 Javascript 使用浏览器对象与远程服务器进行通信。这个的一般用例是能够更新客户端的界面而无需转到另一个页面。在我们开始之前,请注意几句话。

  • Ajax is not recommended for login authentication and posting forms
  • Users can turn off Javascript, or may be restricted from running Javascript due to IT policies
  • With this in mind it is advised that you do not use AJAX as the sole solution for critical user functionality! Always have a fallback!
  • 不建议将 Ajax 用于登录身份验证和发布表单
  • 用户可以关闭 Javascript,或者可能因 IT 政策而被限制运行 Javascript
  • 考虑到这一点,建议您不要使用 AJAX 作为关键用户功能的唯一解决方案!总有退路!

Note: This community wiki post uses JQuery to show the example AJAX calls. It's recommended for newcomers as it hides the browser compatibility issues of making AJAX calls. Please check the JQuery websitefor more information on JQuery.

注意:此社区 wiki 帖子使用 JQuery 显示示例 AJAX 调用。推荐给新手,因为它隐藏了进行 AJAX 调用的浏览器兼容性问题。有关JQuery的更多信息,请查看JQuery 网站

Note: The examples use communication with a PHP server, but any server side language will work.

注意:示例使用与 PHP 服务器的通信,但任何服务器端语言都可以使用。

AJAX Callbacks

AJAX 回调

First we have an AJAX call. In the AJAX call you setup callback handlers for the different types of events that can occur. A common misconception can be shown in the following code:

首先,我们有一个 AJAX 调用。在 AJAX 调用中,您可以为可能发生的不同类型的事件设置回调处理程序。下面的代码显示了一个常见的误解:

// Incorrect!
function makeAjaxCall() {
  var result = $.ajax({
    url: 'ajax/test.html'
  });

  return result;
}

The problem here is that when your browser makes an AJAX request, it can either come back successful, or as a failure. For example if you try an access a page that doesn't exist, or if the server has an internal error. To keep things as organized as possible, AJAX requires that you create callback functions to handle the data request. The correct way is as follows:

这里的问题是,当您的浏览器发出 AJAX 请求时,它可能会成功返回,也可能会失败。例如,如果您尝试访问不存在的页面,或者服务器出现内部错误。为了使事情尽可能有条理,AJAX 要求您创建回调函数来处理数据请求。正确的方法如下:

// Correct!
function makeAjaxCall() {
  $.ajax({
    url: 'ajax/test.html',
    success: function(data) {
      alert('Horray the AJAX call succeeded!');
    },
    error: function(xhr, error) {
      alert('Holy errors batman!');
    }
  });
}

The Nature of AJAX Calls

AJAX 调用的性质

AJAX calls can be either Asynchronous or Synchronous. Asynchronous means that the browser will make the AJAX request and continue doing other things. Synchronous means the browser will stop what it's doing until the AJAX call completes. Here is an example of the differences in the two code wise:

AJAX 调用可以是异步的,也可以是同步的。异步意味着浏览器将发出 AJAX 请求并继续做其他事情。同步意味着浏览器将停止正在执行的操作,直到 AJAX 调用完成。这是两个代码明智差异的示例:

// An asynchronous call
// This is the default
$.ajax({
  url: '/server.php',
  success: function(data) {
    alert('Horray the AJAX call succeeded!');
  },
  error: function(xhr, error) {
    alert('Holy errors batman!');
  }
});
// This will get called right away
myFunction();

Now for a synchronous call:

现在进行同步调用:

// A synchronous call
$.ajax({
  url: '/server.php',
  async: false, // set the property here
  success: function(data) {
    alert('Horray the AJAX call succeeded!');
  },
  error: function(xhr, error) {
    alert('Holy errors batman!');
  }
});
// This won't get called until the AJAX returns!
myFunction();

WARNING: Synchronous calls make it so the browser can't do anything until the browser completes the call. This could potential lock up the browser! Only use this if you REALLY KNOW WHAT YOU'RE DOING! 99% of the time you want asynchronous AJAX calls.

警告:同步调用使得浏览器在浏览器完成调用之前不能做任何事情。这可能会锁定浏览器!仅当您真正知道自己在做什么时才使用它!99% 的情况下您都需要异步 AJAX 调用。

Note: Synchronous calls don't mean you can get out of not setting callback handlers. You still have to deal with the results using callbacks.

注意:同步调用并不意味着您可以不设置回调处理程序。您仍然必须使用回调处理结果。

The Client->Server Communication Path

客户端->服务器通信路径

The AJAX Client Server Communication Path

AJAX 客户端服务器通信路径

This image illustrates how AJAX is used to communicate with a remote server. First the AJAX code interfaces with a browser object, which makes the actual call to the server. The server then processes the request and sends the result back to the browser, which then looks at the result of the call to determine if it needs to call the success handler, or the error handler. However, there is one issue that can prevent communication at all, which is commonly known as the same origin policy.

此图说明了如何使用 AJAX 与远程服务器进行通信。首先,AJAX 代码与浏览器对象接口,后者对服务器进行实际调用。然后服务器处理请求并将结果发送回浏览器,浏览器然后查看调用结果以确定它是否需要调用成功处理程序或错误处理程序。但是,有一个问题可以完全阻止通信,这就是通常所说的同源策略。

NoteFrom the perspective of the server, the AJAX call will look as if the client had made the request manually. That means the server can utilize things like sessions and other client specific data.

注意从服务器的角度来看,AJAX 调用看起来就像是客户端手动发出请求一样。这意味着服务器可以利用诸如会话和其他客户端特定数据之类的东西。

Same Origin Policy

同源政策

The same origin policy basically means that if your AJAX call is from a page hosted on http://www.mysite.com, you can't make a call to http://www.othersite.comas illustrated here:

同源策略基本上意味着,如果您的 AJAX 调用来自托管在 上的页面http://www.mysite.com,则无法调用http://www.othersite.com如下所示:

Same origin policy blocking a request

阻止请求的同源策略

One way that you can get around this is through a proxy service. This is where you interface with a script on the same server, which in turn interfaces with the site you wish, through CURL calls for example. The following illustrates this proxy method in question:

解决此问题的一种方法是通过代理服务。这是您与同一服务器上的脚本交互的地方,该脚本又与您希望的站点交互,例如通过 CURL 调用。下面说明了这个有问题的代理方法:

Same origin proxy workaround

同源代理解决方法

WARNINGNote that the third party server will not see the request as coming from the client, but as coming from the server. Some servers frown upon the same IP making many calls to their servers. This could get you blocked, so verify that the site in question is okay with this setup.

警告请注意,第三方服务器不会将请求视为来自客户端,而是来自服务器。一些服务器不喜欢同一个 IP 多次调用他们的服务器。这可能会使您被阻止,因此请验证相关站点是否适合此设置。

Note: There are some instances where same origin policy doesn't apply, such as Google Chrome extension calls (you have to set permissions for each site though), certain Greasemonkey calls, and Adobe Air.

注意:在某些情况下,同源策略不适用,例如 Google Chrome 扩展程序调用(尽管您必须为每个站点设置权限)、某些 Greasemonkey 调用和 Adob​​e Air。

Now the final concept to go over is how the server returns data for the client to interact with.

现在要讨论的最后一个概念是服务器如何返回数据以供客户端交互。

AJAX Data Return

AJAX 数据返回

Since it's a very popular option, we'll use JSON, or (J)ava(S)cript (O)bject (N)otation, to pass back the data. JSON basically looks like this:

由于这是一个非常流行的选项,我们将使用 JSON 或 (J)ava(S)cript (O)bject (N)otation 来传回数据。JSON 基本上是这样的:

{
    color: "red",
    value: "#f00"
}

This string can be turned into a JavaScript object, providing easy access to the server results.

此字符串可以转换为 JavaScript 对象,从而可以轻松访问服务器结果。

WARNINGSince this is valid JavaScript, many people use eval()to quickly create js objects. Please don't do this. It opens you up to security issues if the result has malicious code in it. Always use a JSON parser that checks for secure data!

警告由于这是有效的 JavaScript,许多人使用eval()快速创建 js 对象。请不要这样做。如果结果中包含恶意代码,则会导致您面临安全问题。始终使用 JSON 解析器来检查安全数据!

Using the previous example, we can access the different values like so:

使用前面的示例,我们可以像这样访问不同的值:

$.ajax({
  url: '/server.php',
  // It's a good idea to explicitly declare the return type
  dataType: 'json',
  success: function(json) {
    alert("The color is: " + json.color + " and the value is: " + json.value);
  },
  error: function(xhr, error) {
    alert('Holy errors batman!');
  }
});

Notice how easy it is to access the values of the return. Another popular option is to retrieve HTML from a server and inject it into a <div>or other element. Here is an example of this:

请注意访问返回值是多么容易。另一个流行的选择是从服务器检索 HTML 并将其注入到一个<div>或其他元素中。这是一个例子:

$.ajax({
  url: '/server.php',
  // It's a good idea to explicitly declare the return type
  dataType: 'html',
  success: function(html) {
    $("#mydiv").html(html);
  },
  error: function(xhr, error) {
    alert('Holy errors batman!');
  }
});

// Some JS/HTML here

<div id="mydiv"></div>

In the case of a successful return, the contents of the <div>will be populated with the return HTML.

在成功返回的情况下,<div>将使用返回 HTML 填充的内容。

TODO: Dealing with securing against malicious HTML injection?

待办事项:如何防止恶意 HTML 注入?

Conclusion

结论

This concludes the community wiki post on AJAX. I hope it will be useful in helping you understand AJAX, or as an easy way to answer common questions about it.

关于 AJAX 的社区 wiki 帖子到此结束。我希望它有助于帮助您理解 AJAX,或者作为回答有关它的常见问题的简单方法。