ajax,json,跨域jsonp总结
前言:本篇文章总结一下ajax,书本上都是基础知识的介绍,但是没有实例,所以我参照慕课网上的课程,结合实际例子进行总结,其中课程中后台是用php写的,本篇文章不做介绍。 1.ajax作用使用了ajax技术的网页,通过在后台跟服务器进行少量的数据交换,网页就可以实现异步的局部更新。 2.XMLHttpRequest对象的创建
实例化XMLHttpRequest对象: 3.HTTP请求
4. XMLHttpRequest发送请求XHR对象有两个方法:
例子: 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取得响应
.readyState属性 var request = new XMLHttpRequest(); request.open("GET",true); request.send(); request.onreadystatechange = function(){ if(request.readyState === 4 && request.status === 200){ //做一些事情 request.responseText } } 6.一个例子
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":"郭靖",{"name":"黄蓉","age":30}]}'; var jsonobj = eval('('+ jsondata+')'); alert(jsonobj.staff[0].name); //JASON.parse var jsondata = '{"staff":[{"name":"洪七","age":30}]}'; var jsonobj = JASON.parse(jsondata); alert(jsonobj.staff[0].name); eval的方式解析json字符串,不会管json字符串合不合法,并会执行字符串中的js代码,会很不安全 (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","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实现ajaxjQuery.ajax([settings]),settings给出了很多的设定值,可以用一些常用的设定值完成请求
用jquery实现刚才的例子
//首先页面载入完成以后执行的代码 $(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",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); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |