AJAX入门

Ajax笔记javascript

一、 Ajax定义及其工做原理php

Ajax 由 HTML、JavaScript 技术、DHTML 和 DOM 组成,这一杰出的方法能够将笨拙的 Web 界面转化成交互性的 Ajax 应用程序。java

 

二、 建立XMLHttpRequest对象ajax

对于Ajax,最核心的一个对象是XMLHttpRequest,全部的Ajax操做都离不开对这个对象的操做浏览器

    xmlHttp = new XMLHttpRequest();
    xmlHttp =new ActiveXObject(‘Microsoft.XMLHTTP’);

 

三、 XMLHttpRequest对象相关方法服务器

    XMLHttpRequest.open(传递方式,地址,是否异步请求)//打开请求
    XMLHttpRequest.onreadystatechange//准备就绪执行
    XMLHttpRequest.responseText//获取执行结果
并发

四、一个简单的例子框架

index.php文件中异步

    <script src="ajax.js" type="text/javascript"></script>
    <a href="#" onclick="funAjax('lgx')" > show lgx </a>
    <a href="#" onclick="funAjax('zbj')" > show zbj </a>
    <div id="show"></div>

 

ajax.js 文件中
     var xmlHttp;
    function $_xmlHttp(){
        if(window.XMLHttpRequest){
            xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
        }else if(window.ActiveXObject){
            xmlHttp = new XMLHttpRequest();
        }
    }
    function funAjax(id){
        $_xmlHttp();
        xmlHttp.open("get","chuli.php?id="+id,true);
        xmlHttp.onreadystatechange = change;
        xmlHttp.send(null);
    }
    function change(){
        var changeResult = xmlHttp.responseText;
        document.getElementById('show').innerHTML = changeResult;
    }

chuli.php文件中ide

     <?php 
        $str = $_GET['id'];
        for($i = 0; $i <10; $i++)
        echo $str;
        exit;
    ?>

五、 比较标准的ajax框架

    var http_request = false;
    function createRequest(url) {
    //初始化对象并发出XMLHttpRequest请求
        http_request = false;
        if (window.XMLHttpRequest) { //Mozilla等其余浏览器
            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("不能建立XMLHTTP实例!");
            return false;
        }
        http_request.onreadystatechange = alertContents; //指定响应方法
        http_request.open("GET", url, true); //发出HTTP请求
        http_request.send(null);
        }
        function alertContents() { //处理服务器返回的信息
        if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            alert(http_request.responseText);
        } else {
            alert('您请求的页面发现错误');
                }
            }
        }
相关文章
相关标签/搜索