什么是 AJAX,它是如何工作的? [英] What is AJAX and how does it work?

查看:47
本文介绍了什么是 AJAX,它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

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

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

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

解决方案

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

  • 不建议将 Ajax 用于登录身份验证和发布表单
  • 用户可以关闭 Javascript,或者可能因 IT 政策而被限制运行 Javascript
  • 考虑到这一点,建议您不要将 AJAX 用作关键用户功能的唯一解决方案!总是有后备!

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

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

AJAX 回调

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

//不正确!函数 makeAjaxCall() {var 结果 = $.ajax({网址:'ajax/test.html'});返回结果;}

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

//正确!函数 makeAjaxCall() {$.ajax({url: 'ajax/test.html',成功:功能(数据){alert('天啊,AJAX 调用成功了!');},错误:函数(xhr,错误){alert('神圣的错误蝙蝠侠!');}});}

AJAX 调用的性质

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

//一个异步调用//这是默认的$.ajax({url: '/server.php',成功:功能(数据){alert('天啊,AJAX 调用成功了!');},错误:函数(xhr,错误){alert('神圣的错误蝙蝠侠!');}});//这将立即被调用我的功能();

现在进行同步调用:

//一个同步调用$.ajax({url: '/server.php',async: false,//在这里设置属性成功:功能(数据){alert('天啊,AJAX 调用成功了!');},错误:函数(xhr,错误){alert('神圣的错误蝙蝠侠!');}});//在 AJAX 返回之前不会调用它!我的功能();

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

注意:同步调用并不意味着您可以不设置回调处理程序.您仍然需要使用回调来处理结果.

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

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

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

同源政策

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

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

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

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

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

AJAX 数据返回

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

<代码>{红色",值:#f00"}

这个字符串可以变成一个 JavaScript 对象,提供对服务器结果的轻松访问.

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

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

$.ajax({url: '/server.php',//显式声明返回类型是个好主意数据类型:'json',成功:函数(json){alert("颜色为:" + json.color + ",值为:" + json.value);},错误:函数(xhr,错误){alert('神圣的错误蝙蝠侠!');}});

请注意访问返回值是多么容易.另一个流行的选择是从服务器检索 HTML 并将其注入

或其他元素.下面是一个例子:

$.ajax({url: '/server.php',//显式声明返回类型是个好主意数据类型:'html',成功:函数(html){$("#mydiv").html(html);},错误:函数(xhr,错误){alert('神圣的错误蝙蝠侠!');}});//这里有一些 JS/HTML<div id="mydiv"></div>

在成功返回的情况下,

的内容将填充返回 HTML.

TODO:如何防范恶意 HTML 注入?

结论

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

Possible Duplicate:
How does AJAX work?

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, 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 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!

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 website for more information on JQuery.

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

AJAX Callbacks

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:

// 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:

// 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 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:

// 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.

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

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.

Note From 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.

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.com as illustrated here:

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:

WARNING Note 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.

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.

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

AJAX Data Return

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:

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

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

WARNING Since 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!

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:

$.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.

TODO: Dealing with securing against malicious HTML injection?

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,它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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