E027Web學習筆記-Ajax和JSON

一、Ajax

1、Ajax概述

AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML);

AJAX 不是新的編程語言,而是一種使用現有標準的新方法;

AJAX 最大的優點是在不重新加載整個頁面的情況下,可以與服務器交換數據並更新部分網頁內容;

AJAX 不需要任何瀏覽器插件,但需要用戶允許JavaScript在瀏覽器上執行;

 

2、同步和異步(在客戶端和服務器相互通信的基礎上)

同步:

客戶端必須等待服務器的響應,等待期間客戶端不能進行其他操作;

異步:

客戶端不需要等待服務器的響應,在服務器處理請求的過程中客戶端可以進行其他操作;

 

3、作用

提升用戶體驗!

 

4、兩種實現方式

原生JS實現方式(瞭解);

JQuery三種實現方式:

①$.ajax()

②$.get()

③$.post()

 

5、JS原生實現

代碼演示:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="button" value="發送異步請求" onclick="fun();">
    <input id="btn" type="button" value="這裏顯示拿到的數據">
</body>
<script type="text/javascript">
    function fun() {
        //發送異步請求
        //1、創建核心對象
        var xmlHttp;
        if (window.XMLHttpRequest){
            //  IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼
            xmlHttp=new XMLHttpRequest();
        }else{
            // IE6, IE5 瀏覽器執行代碼
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        //2、建立連接
        //參數說明:
        // 2.1、請求方式:get或者post;
        //如果是get,請求參數在url後面拼接,send方法空參,xmlHttp.open("GET","test.txt?username=zibo",true);;
        //如果是get,請求參數在send中定義,xmlHttp.send("username=zibo");;
        // 2.2、請求的URL;
        // 2.3、同步或異步請求,true是異步,false是同步;
        xmlHttp.open("GET","js_ajax?username=zibo",true);
        //3、發送請求
        xmlHttp.send();

        //4、接收並處理來自服務器的響應
        //接收方式:xmlHttp.responseText;
        //接收時間:服務器響應成功之後
        xmlHttp.onreadystatechange=function(){
            if (xmlHttp.readyState===4 && xmlHttp.status===200) {
                document.getElementById("btn").setAttribute("value",xmlHttp.responseText);
            }
        }
    }
</script>
</html>

Servlet:

package com.zibo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/js_ajax")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、獲取請求參數
        String username = req.getParameter("username");
        //2、打印username
        System.out.println("用戶:"+username);
        //3、響應
        resp.getWriter().write("hello : " + username);
    }
}

文件位置圖:

運行結果:

 

6、JQuery實現

方式一($.ajax())

代碼演示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="jquery-3.4.1.min.js"></script>
    <title>Title</title>
</head>
<body>
    <input type="button" value="發送異步請求" onclick="fun();">
</body>
<script type="text/javascript">
    function fun() {
        //發送異步請求
        $.ajax({
            url:"js_ajax",//請求路徑
            type:"POST",
            // data:"username=zibo&age=23",//寫法一,不推薦
            data:{"username":"zibo","age":23},//寫法二,推薦
            success:function (data) {
                alert(data);
            },//執行成功的回調函數!
            error:function () {
                alert("執行出錯的回調函數!");
            },//執行出錯的回調函數
            dataType:"text"//設置接收到的相應格式的數據

        });
    }
</script>
</html>

運行結果:

方式二($.get())

代碼演示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="jquery-3.4.1.min.js"></script>
    <title>Title</title>
</head>
<body>
    <input type="button" value="發送異步請求" onclick="fun();">
</body>
<script type="text/javascript">
    function fun() {
        //發送異步請求
        $.get("js_ajax",{"username":"DongMei","age":"23"},function (data) {
            alert(data);
        },"text");
    }
</script>
</html>

運行結果:

 

方式三($.post())

與$.get()一樣,只需要將get更改爲post;

 

二、JSON

1、JSON簡介

JSON: JavaScript Object Notation(JavaScript 對象表示法);

JSON 是存儲和交換文本信息的語法。類似 XML;

JSON 比 XML 更小、更快,更易解析;

 

2、語法

①數據在名稱/值對中:

1、JSON是由鍵值對構成的;
2、鍵要用引號(單雙都行)引起,也可以不引;
3、取值範圍:
數字(整數或浮點數)
字符串(在雙引號中)
邏輯值(true 或 false)
數組(在中括號中)
對象(在大括號中)
null,不常用

②數據由逗號分隔

③大括號保存對象

④中括號保存數組

 

3、定義、嵌套和獲取值的演示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script type="text/javascript">
    //1、定義基本格式
    var student = {"name":"zibo","age":23,gender:true};
    document.write(student.name + "<br/>");

    //2、嵌套:{} -> []
    var students = {
        "student":[
        {"name":"ZiBo","age":23,gender:true},
        {"name":"DongMei","age":23,gender:false},
        {"name":"zibo","age":23,gender:true}
        ]
    };
    document.write(students.student[1].name + "<br/>");

    //3、嵌套:[] -> {}
    var stus = [
        {"name":"ZiBo","age":23,gender:true},
        {"name":"DongMei","age":23,gender:false},
        {"name":"zibo","age":23,gender:true}
    ];
    document.write(stus[1].age);
</script>
</html>

 

4、JSON解析器

常見解析器:JsonLib,Gson,fastjson,jackson(Spring MVC內置解析器)

 

5、Java對象轉JSON:

jackson使用步驟:

第一步:導入jackson jar包,

下載地址是

鏈接:https://pan.baidu.com/s/1-p9vJMNl5NiyOn0enaWtvw 
提取碼:twqo 

第二步:創建jackson核心對象 ObjectMapper;

第三步:調用ObjectMapper相關方法進行轉換;
 

轉換方法:
write(參數1,obj)
參數1:
File:將obj對象轉換成JSON字符串,並保存到執行的文件中;
Writer:將obj對象轉換成JSON字符串,並將JSON字符串填充到字符輸出流;
OutputStream:將obj對象轉換成JSON字符串,並將JSON字符串填充到字節輸出流;

writeValueAsString(obj):將obj對象轉換爲JSON字符串;

代碼演示:

package com.zibo.test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zibo.Student;
import org.junit.Test;

public class JTest {
    @Test
    public void test1() throws Exception {
        //1、創建對象
        Student student = new Student();
        student.setName("zibo");
        student.setAge(23);
        student.setGender(true);
        //2、創建jackson核心對象 ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //3、調用ObjectMapper相關方法進行轉換
        String json = mapper.writeValueAsString(student);
        System.out.println(json);
    }
}

運行結果:

註解:

1、@JsonIgnore:排除屬性;
2、@JsonFormat:屬性值的格式化;

示例:

//注意註解是寫在實體類中的
package com.zibo;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class Student {
    private String name;
    private int age;
    @JsonIgnore
    private boolean gender;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isGender() {
        return gender;
    }

    public void setGender(boolean gender) {
        this.gender = gender;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

複雜的Java對象轉JSON:

List:數組;

Map:與Java對象格式一致;

代碼示例:

package com.zibo.test;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zibo.Student;
import org.junit.Test;

import java.util.*;

public class JTest {
    @Test
    public void test1() throws Exception {
        //1、創建對象
        Student student1 = new Student();
        student1.setName("ZiBo");
        student1.setAge(23);
        student1.setGender(true);
        student1.setBirthday(new Date());
        Student student2 = new Student();
        student2.setName("DongMei");
        student2.setAge(23);
        student2.setGender(false);
        student2.setBirthday(new Date());
        Student student3 = new Student();
        student3.setName("zibo1");
        student3.setAge(23);
        student3.setGender(true);
        student3.setBirthday(new Date());
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        Map<Integer,Student> map = new HashMap<>();
        map.put(1,student1);
        map.put(2,student2);
        map.put(3,student3);
        //2、創建jackson核心對象 ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //3、調用ObjectMapper相關方法進行轉換
        String json1 = mapper.writeValueAsString(list);
        String json2 = mapper.writeValueAsString(map);
        System.out.println(json1);
        System.out.println(json2);
    }
}

運行結果:

 

6、JSON轉Java對象

代碼示例:

package com.zibo.test;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zibo.Student;
import org.junit.Test;

import java.util.*;

public class JTest {
    @Test
    public void test1() throws Exception {
        //1、初始化JSON字符串
        String json = "{\"name\":\"zibo\",\"age\":23,\"gender\":true}";
        //2、創建jackson核心對象 ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //3、調用ObjectMapper相關方法進行轉換
        Student stu = mapper.readValue(json,Student.class);
        System.out.println(stu.getName());//zibo
    }
}

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章