您好,欢迎访问一九零五行业门户网

什么是ajax?关于ajax的具体介绍

ajax 本身本不是一门技术,而是在2005年由jesse james garrett首创的描述为一个“新”途径来应用许多已存在的技术,包括:html 或者 xhtml, cascading style sheets, javascript, the document object model, xml, xslt, 和最重要的 xmlhttprequest object。
当把这些技术结合到ajax模型里的时候,web app可以快速地,逐渐地更新用户界面来取代以前的刷新整个浏览界面,这使得应用更快和用户使用体验更好。
尽管x在ajax里面代表xml,json由于其更轻和是javascript的一部分等优点而被更多的使用。ajax模型里面的json和xml都是用来包装数据信息的。
什么是ajax?ajax 代表 asynchronous javascript and xml. 简而言之, 他是用 xmlhttprequestobject 来和服务器交流的方式. 它可以以不同的方式发送和接收信息, 包括 json, xml, html, 和text文件. ajax最有吸引力的特性是 异步, 这意味着它可以在不刷新页面的情况下同服务器交流,交换数据更新页面。
ajax的主要两个主要特性:
不刷新页面请求数据
从服务器获取数据
step 1 – 如何请求为了用javascript请求服务器,我们要实例化一个有必要功能的对象。这是xmlhttprequest的来源。起初internet explorer实现了一个被称为xmlhttp的activex对象。 之后,mozilla, safari,和其他浏览器厂商陆续实现了xmlhttprequest对象来支持这个方法和类似于microsof的activex对象功能。同时,microsoft也实现了xmlhttprequest。
// old compatibility code, no longer needed.
if (window.xmlhttprequest) { // mozilla, safari, ie7+ ...
    httprequest = new xmlhttprequest();
} else if (window.activexobject) { // ie 6 and older
    httprequest = new activexobject(microsoft.xmlhttp);
}
注意:以上代码只做解释作用,只是创建了xmlhttp的实例。可以跳到step 3去看更实用的例子。
请求之后,我们需要接收请求结果。在这个阶段,我们需要告诉xmlhttp请求对象来处理响应的javascript方法,通过配置他的onreadystatechangeproperty方法,如下:
httprequest.onreadystatechange = nameofthefunction;

或者
httprequest.onreadystatechange = function(){
   // process the server response here.
};
在声明怎么接受响应之后,我们需要发起请求,通过调用http请求对象的 open() 和 send() 方法,如下:
httprequest.open('get', 'http://www.example.org/some.file', true);
httprequest.send();
open() 的第一个参数是http 请求的方法 – get, post, head, 或者其他服务器支持的方法。方法名全部大写是http标准,不然有些浏览器(例如:firefox)可能会不发器请求。 点击 w3c specs 获得更多关于http请求方法的信息。
第二个参数是要请求的url。从安全方面考虑,默认不能跨域请求url。确保所有页面在同一个域名下,不然调用open()方法,你会得到 permission denied” 错误。 一个常见的跨域是你网站的域名是 domain.tld,但是尝试用 www.domain.tld访问页面。如果真的想跨域请求,查看 http access control。
可选的第三个参数设置这个请求是同步还是异步的。如果是true (默认值), javascript 会继续执行,用户操作页面的同时,服务器返回数据。这是 ajax的a。
send()方法的参数可以是你想发送到服务器的任意数据(post)。表单数据必须是服务器能解析的形式,例如查询字符串:
name=value&anothername=+encodeuricomponent(myvar)+&so=on
或者其他形式,例如 multipart/form-data,json, xml, 等等。
注意如果你想post数据,你可能要设置请求的mime type。例如我们把下面代码放在调用send()之前,来把表单数据当查询数据发送:
httprequest.setrequestheader('content-type', 'application/x-www-form-urlencoded');
step 2 – 处理服务器响应请求的时候,我们已经提供了处理响应的javascript方法:
httprequest.onreadystatechange = nameofthefunction;

这个方法做什么?首先,我们需要检查请求状态。如果张台值为xmlhttprequest.done (4),意味着已经接受了所有服务器的响。
if (httprequest.readystate === xmlhttprequest.done) {
   // everything is good, the response was received.
} else {
   // not ready yet.
}
readystate 全部可能的值,可以在 xmlhttprequest.readystate 查看,如下:
0 (uninitialized) or (请求未初始化)
1 (loading) or (服务器建立连接)
2 (loaded) or (请求被接收)
3 (interactive) or (执行请求)
4 (complete) or (request finished and response is ready请求完成响应到位)
value state description
0 unsent client has been created. open() not called yet.
1 opened open() has been called.
2 headers_received send() has been called, and headers and status are available.
3 loading downloading; responsetext holds partial data.
4 done the operation is complete.
(source)
接下来,检查http响应的 response code 。查看 w3c看到可能的值。下面例子我们用response code是不是等于200来判断ajax请求是否成功。
if (httprequest.status === 200) {
   // perfect!
} else {
   // there was a problem with the request.
   // for example, the response may have a 404 (not found)
   // or 500 (internal server error) response code.
}
检查完响应值后。我们可以随意处理服务器返回的数据,有两个选择获得这些数据:
httprequest.responsetext – 返回服务器响应字符串
httprequest.responsexml – 返回服务器响应xmldocument 对象 可以传递给javascript dom 方法
上面的代码只有在异步的情况下有效(open() 的第三个参数设置为true)。如果你用同步请求,就没必要指定一个方法。但是我们不鼓励使用同步请求,因为同步会导致极差的用户体验。
step 3 – 一个简单的例子我们把上面的放在一起合成一个简单的http请求。我们的javascript 将请求一个html 文档, test.html, 包含一个字符串 i'm a test.然后我们alert()响应内容。这个例子使用普通的javascript — 没有引入jquery, html, xml 和 php 文件应该放在同一级目录下。
<button id="ajaxbutton" type="button">make a request</button>
<script>
(function() {
 var httprequest;
 document.getelementbyid(ajaxbutton).addeventlistener('click', makerequest);
function makerequest() {
   httprequest = new xmlhttprequest();
if (!httprequest) {
     alert('giving up :( cannot create an xmlhttp instance');
     return false;
   }
   httprequest.onreadystatechange = alertcontents;
   httprequest.open('get', 'test.html');
   httprequest.send();
 }
function alertcontents() {
   if (httprequest.readystate === xmlhttprequest.done) {
     if (httprequest.status === 200) {
       alert(httprequest.responsetext);
     } else {
       alert('there was a problem with the request.');
     }
   }
 }
})();
</script>
在这个例子里:
用户点击make a request” 按钮;
事件调用 makerequest() 方法;
请求发出,然后 (onreadystatechange)执行传递给 alertcontents();
alertcontents() 检查响应是否 ok, 然后 alert() test.html 文件内容。
注意 1: 如果服务器返回xml,而不是静态xml文件,你必须设置response headers 来兼容i.e.。如果你不设置headercontent-type: application/xml, ie 将会在你尝试获取 xml 元素之后抛出一个javascript object expected 错误 。
注意 2: 如果你不设置header cache-control: no-cache 浏览器将会缓存响应不再次提交请求,很难debug。你可以添加永远不一样的get 参数,例如 timestamp 或者 随机数 (查看 bypassing the cache)
注意 3: 如果 httprequest 变量是全局的,混杂调用 makerequest()会覆盖各自的请求,导致一个竞争的状态。在一个closure 里声明 httprequest 本地变量 来避免这个问题。
在发生通信错误(如服务器崩溃)、onreadystatechange方法会抛出一个异常,当访问响应状态。为了缓解这个问题,你可以用ry…catch包装你的if...then 语句:
function alertcontents() {
 try {
   if (httprequest.readystate === xmlhttprequest.done) {
     if (httprequest.status === 200) {
       alert(httprequest.responsetext);
     } else {
       alert('there was a problem with the request.');
     }
   }
 }
 catch( e ) {
   alert('caught exception: ' + e.description);
 }
}
step 4 – 使用 xml 响应在前面的例子里,在获取到响应之后,我们用request 对象responsetext 属性获得 test.html 文件内容。现在让我们尝试获取responsexml 属性。
首先,让我们创建一个有效的xml文档,留着待会我们请求。(test.xml)如下:
<?xml version="1.0" ?>
<root>
   i'm a test.
</root>
在这个脚本里,我们只要修改请求行为:
...
onclick=makerequest('test.xml')>
...
然后在alertcontents()里,我们需要把 alert(httprequest.responsetext); 换为:
var xmldoc = httprequest.responsexml;
var root_node = xmldoc.getelementsbytagname('root').item(0);
alert(root_node.firstchild.data);
这里获得了responsexml的xmldocument,然后用 dom 方法来获得包含在xml文档里面的内容。你可以在here查看test.xml,在here查看修改后的脚本。
step 5 – 使用数据返回最后,让我们来发送一些数据到服务器,然后获得响应。我们的javascript这次将会请求一个动态页面,test.php将会获取我们发送的数据然后返回一个计算后的字符串 - hello, [user data]!,然后我们alert()出来。
首先我们加一个文本框到html,用户可以输入他们的姓名:
<label>your name:
 <input type="text" id="ajaxtextbox" />
</label>
<span id="ajaxbutton" style="cursor: pointer; text-decoration: underline">
 make a request
</span>
我们也给事件处理方法里面加一行获取文本框内容,并把它和服务器端脚本的url一起传递给 makerequest() 方法:
 document.getelementbyid(ajaxbutton).onclick = function() {
     var username = document.getelementbyid(ajaxtextbox).value;
     makerequest('test.php',username);
 };
我们需要修改makerequest()方法来接受用户数据并且传递到服务端。我们将把方法从 get 改为 post,把我们的数据包装成参数放到httprequest.send():
function makerequest(url, username) {
...
httprequest.onreadystatechange = alertcontents;
   httprequest.open('post', url);
   httprequest.setrequestheader('content-type', 'application/x-www-form-urlencoded');
   httprequest.send('username=' + encodeuricomponent(username));
 }
如果服务端只返回一个字符串, alertcontents() 方法可以和step 3 一样。然而,服务端不仅返回计算后的字符串,还返回了原来的用户名。所以如果我们在输入框里面输入 “jane”,服务端的返回将会像这样:
{userdata:jane,computedstring:hi, jane!}
要在alertcontents()使用数据,我们不能直接alert responsetext, 我们必须转换数据然后 alert computedstring属性:
function alertcontents() {
 if (httprequest.readystate === xmlhttprequest.done) {
   if (httprequest.status === 200) {
     var response = json.parse(httprequest.responsetext);
     alert(response.computedstring);
   } else {
     alert('there was a problem with the request.');
   }
 }
}
test.php 文件如下:
$name = (isset($_post['username'])) ? $_post['username'] : 'no name';
$computedstring = hi, . $name;
$array = ['username' => $name, 'computedstring' => $computedstring];
echo json_encode($array);
查看更多dom方法, 请查看 mozilla's dom implementation 文档。
以上就是什么是ajax?关于ajax的具体介绍的详细内容。
其它类似信息

推荐信息