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

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

问题描述

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

注意:这是一个社区的wiki后

Note: This is a community wiki post

我常常听到AJAX被用于提供动态内容的用户。这是什么,它​​是如何工作的?

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

推荐答案

AJAX,或(A)同步(J)avascript(A)次(X)ML(其中有趣的是倾向于使用JSON的更多,这些天),是在其中的Javascript使用浏览器对象的系统与远程服务器进行通信。一般情况下使用的,这是要能够更新客户端的接口,而无需去到另一页。在我们开始之前,虽然,谨慎的几句话。

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.

  • 在阿贾克斯不推荐用于登录认证和发布形式
  • 用户可以关闭JavaScript,或者可以运行Javascript的限制,由于它的政策
  • 在考虑到这一点,建议你的不使用AJAX作为关键用户功能的唯一解决方案!总有一个备用!

注意:这个社区的wiki后使用jQuery来展示AJAX调用的例子。我们推荐的新人,因为它隐藏使得AJAX调用的浏览器兼容性问题。请检查 JQuery的网站的jQuery的更多信息。

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.

注意:本示例使用通信的方式与PHP服务器,但任何服务器端语言都会正常工作

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

首先我们有一个AJAX调用。在AJAX调用您的不同类型可能发生的事件设置回调处理程序。一个常见的​​误解可以通过以下code显示:

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;
}

这里的问题是,当你的浏览器发出一个AJAX请求时,它可以回来成功,或者为失败。例如,如果你试图访问一个不存在的页面,或者如果该服务器有一个内部错误。为了让事情有组织地,AJAX要求创建回调函数来处理数据请求。正确的方法是如下:

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!');
    }
  });
}

AJAX的自然召唤

AJAX调用可以是异步或同步。异步意味着浏览器将使得AJAX请求,并继续做其他的事情。同步意味着浏览器将停止它在做什么,直到AJAX调用完成。下面是两个code明智差异的例子:

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();

现在的同步调用:

// 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();

警告:同步调用使它所以直到浏览器完成呼叫的浏览器不能做任何事情。这可能潜在锁住浏览器!只使用这个,如果你真的知道你在做什么! 99%的时候你要异步Ajax调用。

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.

此图展示了如何AJAX是用于与远程服务器进行通信。第一AJAX的code接口与一个浏览器对象,这使得对服务器的实际调用。然后,服务器处理该请求,并将结果发送回浏览器,然后着眼于调用的结果,以确定它是否需要调用成功处理程序,或错误处理程序。然而,有一个问题,可以prevent沟通可言,这就是俗称的同源策略。

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调用看起来好像客户端已手动提出的要求。这意味着服务器可以利用的东西一样会和其他客户特定的数据。

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.

同源策略基本上意味着,如果你的AJAX调用是驻留在 http://www.mysite.com 的页面时,你不能拨打电话以 http://www.othersite.com 如图所示的位置:

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:

警告请注意,第三方服务器将不会看到该请求是来自客户端,但由于来自服务器。有些服务器看不惯同一个IP使得许多电话到他们的服务器。这可以让你受阻,因此确认有问题的网站是好的,这种设置。

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.

注意:有一些情况下同源策略并不适用,如谷歌Chrome扩展程序呼叫(你必须虽然设置权限为每个站点),某些Greasemonkey的电话,和Adobe AIR。

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.

由于这是一个非常受欢迎的选择,我们将使用JSON,或(J)AVA(S)CRIPT(O)bject(N)浮选,传回数据。 JSON基本上是这样的:

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"
}

此字符串可以变成一个JavaScript对象,可轻松对服务器的访问结果。

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

警告由于这是有效的JavaScript,许多人使用的eval()来快速创建JS对象。 请不要这样做。它会打开你到安全问题,如果结果有恶意code在里面。始终使用JSON解析器来检查安全的数据!

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!

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

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!');
  }
});

注意它是多么容易访问返回的值。另一种流行的选择是从服务器中检索HTML并注入到一个< D​​IV> 或其他元素。下面是这样一个例子:

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>

在一个成功的回报的情况下,内容的&LT; D​​IV&GT; 将填充返回的HTML

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

TODO :与保护,防止恶意HTML注入处理

TODO: Dealing with securing against malicious HTML injection?

这结束对AJAX的社区维基职位。我希望这会帮助你了解AJAX,或作为一种简单的方法来回答常见问题它是有用的。

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天全站免登陆