加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax,json,跨域jsonp总结

发布时间:2020-12-16 01:32:19 所属栏目:百科 来源:网络整理
导读:前言:本篇文章总结一下ajax,书本上都是基础知识的介绍,但是没有实例,所以我参照慕课网上的课程,结合实际例子进行总结,其中课程中后台是用php写的,本篇文章不做介绍。 1.ajax作用 使用了ajax技术的网页,通过在后台跟服务器进行少量的数据交换,网页就

前言:本篇文章总结一下ajax,书本上都是基础知识的介绍,但是没有实例,所以我参照慕课网上的课程,结合实际例子进行总结,其中课程中后台是用php写的,本篇文章不做介绍。

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",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":"郭靖",{"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代码,会很不安全
在线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","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",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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读