ajax笔记
初识Ajax
get请求
let btn = document.getElementById('btn')
        let info = document.getElementById('info')
        btn.onclick = function () {
            let userName = document.getElementById('userName').value;
            let userPwd = document.getElementById('userPwd').value;
            //使用Ajax发送请求需要如下几步
            //1. 创建XMLHttpRequest对象
            let xhr = new XMLHttpRequest()
            //2.准备发送
            xhr.open('get' , 'check.php?userName='+userName+'&userPwd='+userPwd, true)
            //3. 执行发送动作,get的话填null,post填实际数据
            xhr.send(null)        
            //4.指定回调函数
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4 ){
                    if(xhr.status == 200){
                        let data = xhr.responseText
                        if(data == '1'){//成功
                            info.innerHTML = '登陆成功'
                        }
                        else if(data == '2'){
                            info.innerHTML = '用户名或者密码错误'
                        }
                    }
                }
            }   
        }
创建对象
 //1.创建XMLHttpRequest对象
            //标准浏览器
            let xhr = new XMLHttpRequest()
            //IE老版本 ie6
            let xhr1 = new ActiveXObject("Microsoft.XMLHTTP")
            //兼容性处理
            let xhr2 = null
            if(window.XMLHttpRequest){
                xhr = new XMLHttpRequest()
            }
            else{
                xhr = new ActiveXObject('Microsoft.XMLHTTP')
            }
请求参数分析
- 请求方式(get获取数据,post提交数据)
 - 请求地址
 - 设置同步或异步标志位,默认是true表示异步。如果是get请求,那么请求参数必须在url中传递
 
let param = 'userName='+userName+'&userPwd='+userPwd
//encodeURI()用来对中文参数进行编码,防止乱码
xhr.open('get' , 'check.php?'+encodeURI(param) ,true)
xhr.open('post' , '04.php.php' ,true)
执行发送请求
xhr.open(null) //get请求需要加null
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
xhr.open(param) //post在send传递参数,不需要codeURI转码,还必须要设置请求头
指定回调函数
//该函数调用的条件就是readyState发生变化(不包括0到1)
xhr.onreadystatechange = function () {
                if(xhr.readyState == 4){
                    if(xhr.status == 200){ //表示服务器返回的数据正常,不是200的话就表示数据是错误的
                        alert(xhr.responseText)
                    }
                }
            }
xhr.readyState = ?
- 0 表示xhr对象创建完毕
 - 1 表示调用了xhr.send(),已经发送了请求
 - 2 表示浏览器已经收到服务器响应数据
 - 3 表示正在解析数据
 - 4 数据已经解析完成,可以使用了,但是这个数据不一定是正常的
 
json数据格式
json格式的数据和js普通对象区别:
- json数据没有变量
 - json数据结尾没有分号
 - json数据中的键必须用双引号包住
 
{
    "name" : "zhangsan",
    "age" : 12,
    "lover" : ["coding","singing","dancing"],
    "friend" : {
        "high":"180cm",
        "weigth":"80kg"    
        }
}
JQ中的ajax
$.ajax({
    type:'get', //xml json html script text jsonp
    url:'1.php',
    data:{code:code},
    dataType:'json',
    success : function(data){
    },
    error: function(){
    }
})
Ajax跨域
同源策略
- 同源策略是浏览器一种安全策略,所谓同源指的是请求URL地址中的协议,域名和端口都相容,只要其中之一不相同就是跨域
 - 同源策略主要为了保证浏览器的安全性
 - 在同源策略下,浏览器不允许Ajax跨域获取服务器数据
 
解决方法:
- jsonp
 - document.domain+iframe
 - location.hash+iframe
 - window.name + iframe
 - window.postMessage
 - flash等第三方插件
 
jsonp
jsonp原理:
- 静态script标签的src属性进行跨域请求。script标签中的async属性表示异步加载资源,默认情况是同步加载,有此属性时无法用1方法进行跨域请求。
- 必须保证加载顺序
 - 不方便通过程序传递参数
 
 - 动态创建script标签,通过标签的src属性发送请求,这个请求是异步的(jsonp本质)
 
let flag = 1
let script = document.createElement('script')
script.src = 'http://tom.com/data.php?callback=hello&username=zhangsan'
let head = document.getElementsByTagName('head')[0]
head.appendChild(script)
//hello就是回调函数 这就是jsonp的本质:动态创建script标签,然后通过他的src发送跨域请求,然后服务器端响应的数据格式为函数调用,所以在发送请求之前必须先声明一个函数,并且函数名字与参与中传递的名字一致。这里声明的函数由服务器响应的内容(一段js代码)来调用
function hello(data){
    console.log(data.username,data.password) //zhangsan 123456
}
//服务器响应的内容是 函数调用
$arr = array("username"=>"zhangsan","password"=>"123456");
$cb = $_GET['cb'];
echo $cb.'('.json_encode($arr).')';
jq中的jsonp跨域
$(function(){
    $(#btn).click(function(){
        $.ajax({
            type:'get',
            url:'http://tom.com//jsonp.php',
            datatype:'jsonp',
            jsonp:'cb', //jsonp属性的作用就是自定义参数名字 cb=abc 指的是等号前面的键,后端根据这个键获取方法名, jQuery默认是callback
            jsonpCallback:'abc', //回调函数名字,指的是等号后面的值
            data:{}
            success:function(data){
                console.log(data)
            },
            error:function(data){
                console.log(data)
            }
        })
    })
})
 
                    
                
                
            
        
浙公网安备 33010602011771号