Ajax的一点用法

来源:互联网 发布:网络信息安全要学什么 编辑:程序博客网 时间:2024/05/23 15:45

什么是Ajax?

一种快速实现动态网页的技术。

操作过程是什么?

首先你得创建一个服务器(下面是一个简单的nodejs服务器)
var http = require('http');//引入http模块var fs = require('fs') ;//引入fs模块http.createServer(    function(req,res){        console.log(req.url)        //判断请求,根据open函数的get值        if(req.url=="/"){            fs.readFile('Ajax.html',function(error,data){                if(error){                    console.log(error);                    res.end(error.toString())                }else{                    res.end(data.toString())                }            })        }       }).listen(8088,fn(){console.log('这是回调函数')})
创建一个默认页面(路径置于nodejs.exe同等位置、名字见上)
……<body>    <button onclick='loadData()'></button></body>……
网页创建通信对象
<script>    function loadData(){        //创建请求对象        var httpTool;        if(window.XMLHttpRequest) { //如果浏览器有XMLHttpRequest这个对象就创建            httpTool = new XMLHttpRequest()        } else { //没有就创建ActiveXObject(针对老版本浏览器)            httpTool = new ActiveXObject("Microsoft.XMLHTTP")        }       
网页发送请求消息
        //发送网络请求        httpTool.open('get', '自定义的有意义字符串');        //服务器将会以这个字符串作为返回数据的依据        httpTool.send()     
网页监听服务器传回数据
        //监听管道,当步骤为4的时候,后端发数据(w/r)过来        //httpTool.readState;0:请求没有初始化 1:服务器建立连接 2:请求已接受 3:请求处理ing 4:请求完成,响应已经就绪        httpTool.onreadystatechange = function() {            //如果等于4,后端发数据过来了            if(httpTool.readyState==4) {                if(httpTool.status == 200){                    //正确的数据                    //得到数据                    //解析数据                    //dom操作                    console.log(httpTool.responseText);                    //根据上面的结果更新网页                }else if(httpTool.status == 404){                    //不是想要的数据                    console.log(404)                }else{                    console.log('error:'+httpTool.status);                }                console.log(httpTool.responseText);            }else{                //console.log('error');            }        }    }    </script>

Ajax传送数据的一个不足(JSONP产生了?)

尝试用以下的代码创建服务器,不创建网页(注意这里没有创建对象进行监听了,这有个名称叫做跨域访问)
//服务器js代码var http = require('http');http.createServer(    function(req,res){        var data = '{"name":"Shawn","age":18,"0":"NULL"}';        if(req.url=="/ThisIsSendFromServer"){            res.end(data);        }        if(req.url=="/ThisIsFnSendFromServer"){            res.end('fromServer('+data+')');        }       }).listen(8088);//网页访问下面网址http://localhost:8088/ThisIsSendFromServer//任意位置的html代码,使用src获取上面数据,用script会容易解析<html>    ……    <body>    <script src='http://localhost:8088/ThisIsSendFromServer'></script>    </body></html>//下面可真正操作数据<html>    ……    <body>    <script>        fromServer(data){            //自己思考为什么这样就可以获得真正数据            console.log(data);        }    </script>    <script src='http://localhost:8088/ThisIsFnSendFromServer'></script>    </body></html>
原创粉丝点击