AJax全接触
Ajax学习笔记XMLHttpRequest对象的创建xmlhttprequest是一个可以在不重新加载整个页面的情况下进行前后端数据交换的对象 XMLHttpRequest,IE5 IE6不支持;
兼容方法:
var request;
if(window.XMLHttpRequest){
request=new XMLHttpRequest();//兼容IE7+,Firefox,chrome,Opera,safari...
}else{
request=new ActiveXObject("Microsoft.XMLHTTP");//适用于IE5,IE6版本;
}
XMLHttpRequest发送请求
例如: request.open("POST","create.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded ")//设置HTTP头信息,一定要写在open()和send()之间
request.send("name=xxxx&sex=xxx");
XMLHttpRequest取得响应
1:服务器连接已建立,open已经调用了 2:请求已接收,也就是接收到头信息了 3:请求处理中,也就是接收到了响应主体 4:请求已完成,且响应已就绪,也就是响应完成了 var request = new XMLHttpRequest() //建立XHR对象
request.open("GET","get.php",true); //用get方法异步打开get.php
request.send(); //发送请求头信息
request.onreadystatechange=function(){
if(request.readState===4&&request.status===200){
//做一些事情 request.responseText;
}
}
通过onreadystatechange事件 ,对readyState属性进行监听即对服务器的响应进行监听,
a:new一个XHR对象 b:调用open方法 c:send一些数据 d:对过程进行监听,来知道服务器是不是正确地做出了响应,接着可以做一些事情 JSON解析JQuery中的Ajax1、在线引用(百度静态资源公共库) 2、jq实现Ajax(代码如下) $(document).ready(function(){
$("#save").click(function(){
$.ajax({
type:"post",url:"service.php",dataType:"json",data:{
name:$("#staffName").val(),number:$("#staffNumber").val(),sex:$("#staffSex").val(),job:$("#staffJob").val()
},success:function(data){
if(data.success){$("#createResult").html(data.msg)}
else{$("#createResult").html("error: " + data.msg) }
},error:function(jqXHR){
alert("error: "jqXHR.status);
}
});
});
});
javaScript跨域什么事跨域呢?
HTTP默认访问80端口 HTTPS默认访问443端口 所以http访问https肯定是跨域
处理跨域的方法 1、处理跨域方法一 代理 通过在同域名下的web服务器端创建一个代理: 北京服务器(域名:www.beijing.com) 上海服务器(域名:www.shanghai.com) 比如在北京的web服务器的后台(www.beijing.com/proxy-shanghaiservice.php) 2、处理跨域方式二——JSONP(只支持GET请求): 在www.aaa.com页面中: <script>
function jsonp(json){
alert(json["name"]);
}
</script> <script src="http;//www.bbb.com/jsonp.js"></script>
在www.bbb.com页面中: jsonp({‘name’:’xx’,’age’:24}) 3、处理跨域的方法三——XHR2: 1、HTML5提供的XMLHttpRequest Level2已经实现了跨域访问以及其他的一些新功能 2.IE10以下的版本都不支持 3.在服务器端 header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST,GET');
完毕……………………………………….. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |