Ajax

1 ajax 是什么?

ajax是一种技术方案,但并不是一种新技术。它依赖的是现有的CSS/HTML/Javascript,而其中最核心的依赖是浏览器提供的XMLHttpRequest对象,是这个对象使得浏览器可以发出HTTP请求与接收HTTP响应.

1.1 ajax有什么作用

我们使用XMLHttpRequest对象来发送一个Ajax请求。来实现在页面不刷新的情况下和服务端进行数据交互,能够快速,增量更新用户界面,而无需重新加载整个浏览器页面;即异步更新;这使得应用程序更快,更响应用户操作。

范例:

使用GET方法;

 var xhr = new XMLHttpRequest();
      xhr.open('GET','/hello.json');
    xhr.onreadystatechange = function(){
        if(xhr.readyState===4){
            if((xhr.status>=200 &&xhr.status <300)|| xhr.status ==304){
                console.log(xhr.responseText);
                console.log("aa");
            }else{
                alert("服务器异常")
                console.log("bb");
            }
        }
    }
    xhr.send();
Ajax_第1张图片
1.png

使用POST方法:

    var xhr = new XMLHttpRequest();
    xhr.timeou=5000;
    xhr.onload = function(){
            if((xhr.status>=200 &&xhr.status <300)|| xhr.status ==304){
                console.log(xhr.responseText);
                console.log("aa");
            }else{
                alert("服务器异常")
                console.log("bb");
            }
    };
    xhr.open('POST','/server',true)
    xhr.send('username=xiaolhui')

2 封装一个 ajax 函数

    function ajax(opts){
        var url= opts.url;
        var type= opts.type || 'GET';
        var dataType = opts.dataType || 'json';
        var data = opts.data;
        var dataStr= [];
        for(var key in data){
            dataStr.push(key +'='+data[key])
        }
        dataStr=dataStr.join('&');
        var xhr=new XMLHttpRequest();
        xhr.open(type,url,true);
        xhr.onload=function(){
            if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
                if(dataType==='json'){
                    console.log(JSON.parse(xhr.responseText))
                }else{
                    console.log(xhr.responseText)
                }
            }else{
                alert("服务器异常")
            }
        };
        if(type==='GET'){
            url+='?'+dataStr;
        }
        if(type==='POST'){
            xhr.send(dataStr);
        }else{
            xhr.send();
        }
    }
    ajax({
        url:'/hello.json',
        data:{
            city:'杭州'
        }
    })
Ajax_第2张图片
2.png

你可能感兴趣的:(Ajax)