ajax,json,跨域jsonp总结

来源:互联网 发布:数据分析师证书含金量 编辑:程序博客网 时间:2024/05/25 23:26

1.ajax作用

使用了ajax技术的网页,通过在后台跟服务器进行少量的数据交换,网页就可以实现异步的局部更新。

2.XMLHttpRequest对象的创建

  1. 运用HTML和CSS来实现页面,表达信息

  2. 运用XMLHttpRequest和Web服务器进行数据的异步交换

  3. 运用js操作DOM,实现动态的局部更新。

实例化XMLHttpRequest对象:var request = new XMLHttpRequest();

3.HTTP请求

  1. GET:一般用于信息获取,使用URL传递参数,对所发送信息的数量有限制,一般在2000个字符 发送的数据可见,并不安全

  2. POST:一般用于修改服务器上的资源,对所发送信息的数量无限制,发送的数据不是明文可见,较为安全。用于:发送表单数据,新建修改删除

4. XMLHttpRequest发送请求

XHR对象有两个方法:

  1. open(method,url,async):三个参数:发送请求的方式,url请求地址(相对地址和绝对地址),true代表异步,默认是true,设置为false表示同步

  2. send(string):把请求发送到服务器上(GET方式可以不写参数,POST方式不写参数意义不大)

例子:

    request.open("GET","get.php",true);    request.send();    request.open("POST", "post.php", true);    request.send();        request.open("POST", "create.php" ,true);    //设置http的头信息,告诉服务器要发送表单    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    request.send("name=王二狗&sex=男");

5.XMLHttpRequest取得响应

responseText:获得字符串形式的响应数据
responseXML:获得XML形式的响应数据
status和statusText:以数字和文本形式返回HTTP状态码
getAllResponseHeader():获得所有的响应报头
getResponseHeader():查询响应中的某个字段的值

.readyState属性
0:请求未初始化,open还没有调用
1:服务器连接已建立,open已经调用了
2:请求已接收,也就是接收到头信息了
3:请求处理中,也就是接收到响应主体了
4:请求已经完成,且响应已经就绪,也就是响应完成了。

    var request = new XMLHttpRequest();    request.open("GET","get.php",true);    request.send();    request.onreadystatechange = function(){        if(request.readyState === 4 && request.status === 200){            //做一些事情            request.responseText        }    }

6.一个例子

  1. 包含员工的信息,可以通过输入员工的编号查询员工基本信息

  2. 新建员工信息,包含员工姓名,员工编号,员工性别,员工职位。纯HTML页面,用来实现员工查询和新建的页面

php页面,用来实现查询员工和新建员工的后台接口(在此不再多写)

(1)客户端实现

html静态页面实现

<!DOCTYPE html><html><head>    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">    <title>Demo</title>    <style>        *{            font-size: 30px;            line-height: 1.8;        }    </style></head><body>    <h1>员工查询</h1>    <label>请输入员工编号:</label>    <input type="text" id="keyword"/>    <button id="search">查询</button>    <p id="searchResult"></p>    <h1>员工新建</h1>    <label>请输入员工姓名:</label>    <input type="text" id="staffName"/><br>    <label>请输入员工编号:</label>    <input type="text" id="staffNumber"/><br>    <label>请选择员工性别:</label>    <select id="staffSex">        <option></option>        <option></option>    </select><br>    <label>请输入员工职位:</label>    <input type="text" id="staffJob"/><br>    <button id="save">保存</button>    <p id="createResult"></p>        <script src="ajax.js"></script></body></html>

js实现ajax实现页面局部刷新

    //获取查询的按钮,添加一个事件处理函数    document.getElementById("search").onclick = function(){        //发送ajax查询请求并处理        var request = new XMLHttpRequest();        //GET需要把参数写在url中,通过keyword的value值获取        request.open("GET", "service.php?number="+document.getElementById("keyword").value);        request.send();            //将服务器返回的值在页面中局部更新        request.onreadystatechange = function(){            if(request.readyState === 4){                if(request.status === 200){                    //查询成功则局部更新服务器返回结果                    document.getElementById("searchResult").innerHTML = request.reponseText;                }else{                    alert("发生错误"+ request.status);                }            }               }    }        //获取保存的按钮,添加一个事件处理函数    document.getElementById("save").onclick = function(){        //发送ajax查询请求并处理        var request = new XMLHttpRequest();        request.open("POST", "service.php");        //POST传入方式不需要传递参数,但是需要构造参数一下        var data = "name="+document.getElementById("staffName").value                +"&number="+document.getElementById("staffNumber").value                +"&sex="+document.getElementById("staffSex").value                +"&job="+document.getElementById("staffJob").value;        //bug处理              request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");        request.send(data);            //将服务器返回的值在页面中局部更新        request.onreadystatechange = function(){            if(request.readyState === 4){                if(request.status === 200){                    //创建成功后则局部更新服务器返回结果                    document.getElementById("createResult").innerHTML = request.reponseText;                }else{                    alert("发生错误"+ request.status);                }            }               }    }   

(2)JSON实现

eval和parse解析JSON

    //eval    var jsondata = '{"staff":[{"name":"洪七", "age":35}, {"name":"郭靖","age":35}, {"name":"黄蓉", "age":30}]}';    var jsonobj = eval('('+ jsondata+')');    alert(jsonobj.staff[0].name);        //JASON.parse    var jsondata = '{"staff":[{"name":"洪七", "age":35}, {"name":"郭靖","age":35}, {"name":"黄蓉", "age":30}]}';    var jsonobj = JASON.parse(jsondata);    alert(jsonobj.staff[0].name);    

eval的方式解析json字符串,不会管json字符串合不合法,并会执行字符串中的js代码,会很不安全在线json字符串校验工具:JSONLint

(3)JSON改写例子

前后端的约定

{    "success":true,      //代表返回成功与否    "msg":"xxx",    //代表返回成功与不成功时服务器返回的信息}

js代码

document.getElementById("search").onclick = function(){    var request = new XMLHttpRequest();    request.open("GET","service.php?number="+document.getElementById("keyword").value);    request.send();    request.onreadystatechange = function(){        if(request.readyState === 4){            if(request.status === 200){                var data = JSON.parse(request.responseText);                if(data.success){                    document.getElementById("searchResult").innerHTML = data.msg;                }else{                    document.getElementById("searchResult").innerHTML = "出现错误:"+data.msg;                }            }else{                alert("发生错误:"+request.status);            }        }    }}    //获取保存的按钮,添加一个事件处理函数    document.getElementById("save").onclick = function(){        //发送ajax查询请求并处理        var request = new XMLHttpRequest();        request.open("POST", "service.php");        //POST传入方式不需要传递参数,但是需要构造参数一下        var data = "name="+document.getElementById("staffName").value                +"&number="+document.getElementById("staffNumber").value                +"&sex="+document.getElementById("staffSex").value                +"&job="+document.getElementById("staffJob").value;        //bug处理              request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");        request.send(data);            //将服务器返回的值在页面中局部更新        request.onreadystatechange = function(){            if(request.readyState === 4){                if(request.status === 200){                    var data = JSON.parse(request.responseText);                    if(data.success){                        document.getElementById("createResult").innerHTML = data.msg;                    }else{                        document.getElementById("createResult").innerHTML = "出现错误:"+data.msg;                    }                }else{                    alert("发生错误"+ request.status);                }            }               }    }

(4)用jquery实现ajax

jQuery.ajax([settings]),settings给出了很多的设定值,可以用一些常用的设定值完成请求

  1. type:类型,"POST"或者"GET",默认为"GET"

  2. url:发送请求的地址

  3. data:是一个对象,连同请求发送到服务器的数据(POST请求时使用)

  4. dataType:预期服务器返回的数据类型。如果不设定,jquery将自动根据HTTP包MIME信息来智能判断,一般我们采用JSON格式,可以设置为"json"

  5. success:是一个方法,请求成功后的回调函数。传入返回后的数据,以及包含成功代码的字符串

  6. error:是一个方法,请求失败时调用此函数。传入XMLHttpRequest对象

用jquery实现刚才的例子

  1. 首先在HTML中加载jquery的资源库

  2. 改造例子:

//首先页面载入完成以后执行的代码$(document).ready(function(){    $("#search").click(function(){        $.ajax({            type:"GET",            url:"service.php?number="+$("#keyword").val(),            dataType:"json",            success:function(data){                if(data.success){                    $("#searchResult").html(data.msg);                }else{                    $("#searchResult").html("出现错误:"+data.msg);                }            },            error:function(jqXHR){                alert("发生错误:"+jqXHR.status);            }         });    });        $("#save").click(function(){        $.ajax({            type:"POST",            url:"service.php",            dataType:"json",            data:{                name:$("#staffResult").val(),                number:$("#staffNumber").val(),                sex:$("staffSex").val(),                job:$("staffJob").val(),            },            success:function(data){                if(data.success){                    $("createResult").html(data.msg);                }else{                    $("createResult").html("出现错误:"+data.msg);                }            },            error:function(jqXHR){                alert("发生错误:"+jqXHR.status);            }        });    }); });

7.跨域

javascript出于安全方面的考虑,不允许跨域调用其他页面的对象。什么是跨域呢,简单地理解就是因为javascript同源策略的限制,a.com域名下的js无法操作b.com或是c.a.com域名下的对象。

例如:

    www.abc.com/index.html 调用 www.abc.com/service.php      (非跨域)    www.abc.com/index.html 调用 www.efg.com/service.php      (跨域)    www.abc.com/index.html 调用 bbs.abc.com/service.php      (跨域)    www.abc.com/index.html 调用 www.abc.com:81/service.php   (跨域)    www.abc.com/index.html 调用 https://www.abc.com/service.php   (跨域)

(1)JSONP

利用HTML<script>可以跨域的特性

    function handleResponse(response){        alert('My name is' + response.name);    }        var script = document.createElement('script');    script.src = 'http:127.0.0.1:3000/json?callback=handleResponse';    document.body.insertBefore(script, document.body.firstChild);
1 0