服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > 专题栏目 > WEB2.0新技术 > 查看文档

ajax:轻松上路

  ajax是个新产生的术语,专为描述javascript的两项强大性能.这两项性能在多年来一直被网络开发者所忽略,直到最近才使人们开始意识到其重要性。这篇文章将带您浏览整个ajax的基本概貌,并展示两个简单的例子让您轻松上路.

  什么是 ajax?

  ajax (异步 javascript 和 xml) 是个新产生的术语,专为描述javascript的两项强大性能.这两项性能在多年来一直被网络开发者所忽略,直到最近gmail, google suggest和google maps的横空出世才使人们开始意识到其重要性.

  这两项被忽视的性能是:

• 无需重新装载整个页面便能向服务器发送请求.
• 对xml文档的解析和处理.

  步骤 1 ?c "请!" --- 如何发送一个http请求

  为了用javascript向服务器发送一个http请求, 需要一个具备这种功能的类实例. 这样的类首先由internet explorer以activex对象引入, 被称为xmlhttp. 后来mozilla, safari 和其他浏览器纷纷仿效, 提供了xmlhttprequest类,它支持微软的activex对象所提供的方法和属性.

  因此, 为了创建一个跨浏览器的这样的类实例(对象), 可以应用如下代码:

if (window.xmlhttprequest) { // mozilla, safari, ...
    http_request = new xmlhttprequest();
} else if (window.activexobject) { // ie
    http_request = new activexobject("microsoft.xmlhttp");
}

  (上例对代码做了一定简化,这是为了解释如何创建xmlhttp类实例. 实际的代码实例可参阅本篇步骤3.)

  如果服务器的响应没有xml mime-type header,某些mozilla浏览器可能无法正常工作. 为了解决这个问题, 如果服务器响应的header不是text/xml,可以调用其它方法修改该header.

http_request = new xmlhttprequest();
http_request.overridemimetype('text/xml');

  接下来要决定当收到服务器的响应后,需要做什么.这需要告诉http请求对象用哪一个javascript函数处理这个响应.可以将对象的onreadystatechange属性设置为要使用的javascript的函数名,如下所示:

http_request.onreadystatechange = nameofthefunction;

  注意:在函数名后没有括号,也无需传递参数.另外还有一种方法,可以在扉页(fly)中定义函数及其对响应要采取的行为,如下所示:

http_request.onreadystatechange = function(){
    // do the thing
};

  在定义了如何处理响应后,就要发送请求了.可以调用http请求类的open()和send()方法, 如下所示:

http_request.open('get', 'http://www.example.org/some.file', true);
http_request.send(null);

• open()的第一个参数是http请求方式 ?c get, post, head 或任何服务器所支持的您想调用的方式. 按照http规范,该参数要大写;否则,某些浏览器(如firefox)可能无法处理请求.有关http请求方法的详细信息可参考http://www.w3.org/protocols/rfc2616/rfc2616-sec9.html w3c specs
• 第二个参数是请求页面的url.由于自身安全特性的限制,该页面不能为第三方域名的页面.同时一定要保证在所有的页面中都使用准确的域名,否则调用open()会得到"permission denied"的错误提示.一个常见的错误是访问站点时使用domain.tld,而当请求页面时,却使用www.domain.tld.
• 第三个参数设置请求是否为异步模式.如果是true, javascript函数将继续执行,而不等待服务器响应.这就是"ajax"中的"a".

  如果第一个参数是"post",send()方法的参数可以是任何想送给服务器的数据. 这时数据要以字符串的形式送给服务器,如下所示:

name=value&anothername=othervalue&so=on

  步骤 2 ?c "收到!" --- 处理服务器的响应

  当发送请求时,要提供指定处理响应的javascript函数名.

http_request.onreadystatechange = nameofthefunction;

  我们来看看这个函数的功能是什么.首先函数会检查请求的状态.如果状态值是4,就意味着一个完整的服务器响应已经收到了,您将可以处理该响应.

if (http_request.readystate == 4) {
    // everything is good, the response is received
} else {
    // still not ready
}

  readystate的取值如下:

• 0 (未初始化)
• 1 (正在装载)
• 2 (装载完毕)
• 3 (交互中)
• 4 (完成)
(source)

  接着,函数会检查http服务器响应的状态值. 完整的状态取值可参见 w3c site. 我们着重看值为200 ok的响应.

if (http_request.status == 200) {
    // perfect!
} else {
    // there was a problem with the request,
    // for example the response may be a 404 (not found)
    // or 500 (internal server error) response codes
}

  在检查完请求的状态值和响应的http状态值后, 您就可以处理从服务器得到的数据了.有两种方式可以得到这些数据:

• http_request.responsetext ?c 以文本字符串的方式返回服务器的响应
• http_request.responsexml ?c 以xmldocument对象方式返回响应.处理xmldocument对象可以用javascript dom函数

  步骤 3 ?c "万事俱备!" - 简单实例

  我们现在将整个过程完整地做一次,发送一个简单的http请求. 我们用javascript请求一个html文件, test.html, 文件的文本内容为"i'm a test.".然后我们"alert()"test.html文件的内容.

<script type="text/javascript" language="javascript">

    var http_request = false;

    function makerequest(url) {

        http_request = false;

        if (window.xmlhttprequest) { // mozilla, safari,...
            http_request = new xmlhttprequest();
            if (http_request.overridemimetype) {
                http_request.overridemimetype('text/xml');
            }
        } else if (window.activexobject) { // ie
            try {
                http_request = new activexobject("msxml2.xmlhttp");
            } catch (e) {
                try {
                    http_request = new activexobject("microsoft.xmlhttp");
                } catch (e) {}
            }
        }

        if (!http_request) {
            alert('giving up :( cannot create an xmlhttp instance');
            return false;
        }
        http_request.onreadystatechange = alertcontents;
        http_request.open('get', url, true);
        http_request.send(null);

    }

    function alertcontents() {

        if (http_request.readystate == 4) {
            if (http_request.status == 200) {
                alert(http_request.responsetext);
            } else {
                alert('there was a problem with the request.');
            }
        }

    }
</script>
<span
    style="cursor: pointer; text-decoration: underline"
    onclick="makerequest('test.html')">
        make a request
</span>

  本例中:

• 用户点击浏览器上的"请求"链接;
• 接着函数makerequest()将被调用.其参数 ?c html文件test.html在同一目录下;
• 这样就发起了一个请求.onreadystatechange的执行结果会被传送给alertcontents();
• alertcontents()将检查服务器的响应是否成功地收到,如果是,就会"alert()"test.html文件的内容.

  步骤 4 ?c "x-文档" --- 处理xml响应

  在前面的例子中,当服务器对http请求的响应被收到后,我们会调用请求对象的reponsetext属性.该属性包含了test.html文件的内容.现在我们来试试responsexml属性.

  首先,我们新建一个有效的xml文件,后面我们将使用这个文件.该文件(test.xml)源代码如下所示:

<?xml version="1.0" ?>
<root>
    i'm a test.
</root>

  在该脚本中,我们只需修改请求部分:
...
onclick="makerequest('test.xml')">
...

  接着,在alertcontents()中,我们将alert()的代码alert(http_request.responsetext);换成:

var xmldoc = http_request.responsexml;
var root_node = xmldoc.getelementsbytagname('root').item(0);
alert(root_node.firstchild.data);

  这里,我们使用了responsexml提供的xmldocument对象并用dom方法获取存于xml文件中的内容.

扫描关注微信公众号