Java学习路线-47:Ajax学习XMLHttpRequest、XStream、json-lib(3)

json与xml比较

可读性

解码难度

流行度

课时13 13.json-lib的应用

继承关系

public final class JSONArray extends AbstractJSON

   implements JSON, List, Comparable

public final class JSONObject extends AbstractJSON

   implements JSON, Map, Comparable

依赖

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

示例

import net.sf.json.JSONObject;
class Demo {
    public static void main(String[] args)   {
        JSONObject map = new JSONObject();
        map.put("name", "Tom");
        map.put("age", 23);
        String str = map.toString();
        System.out.println(str);
        // {"name":"Tom","age":23}
    }
}

java对象转为json

Person.java

public class Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    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;
    }
}

Demo.java

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Demo {
    public static void main(String[] args) {
        // 对象转JSONObject
        Person person = new Person("Tom", 23);
        JSONObject obj = JSONObject.fromObject(person);
        System.out.println(obj.toString());
        // {"name":"Tom","age":23}
        // List转 JSONArray
        List<Person> list = new ArrayList<Person>();
        list.add(new Person("Tom", 23));
        list.add(new Person("Jack", 23));
        JSONArray array = JSONArray.fromObject(list);
        System.out.println(array.toString());
        // [{"age":23,"name":"Tom"},{"age":23,"name":"Jack"}]
        // map转JSONObject
        Map<String ,String> map = new HashMap<String ,String>();
        map.put("name", "Tom");
        map.put("sex", "male");
        System.out.println(JSONObject.fromObject(map).toString());
        // {"sex":"male","name":"Tom"}
    }
}

课时14 14.打包ajax生成小工具

参数

option{

   method

   url

   asyn

   type

   callback

   params

   data

}

xml

text

json

后端接口

from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route("/json", methods=["GET", "POST"])
def json():
    username = request.args.get("username")
    if request.method == "POST":
        username = request.form.get("username")
        if request.is_json:
            username = request.json.get("username")
    return jsonify({"name": username})
if __name__ == '__main__':
    app.run(debug=True)

封装的工具 ajax-util.js

// 获取XMLHttpRequest对象
function createXMLHttpRequest() {
    try {
        // 大多数浏览器
        return new XMLHttpRequest();
    } catch (e) {
        try {
            // IE6.0
            new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                // IE<=5.5
                new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                console.log("浏览器版本太老了!");
                throw e;
            }
        }
    }
}
// 判断是否为IE浏览器
function isIE() {
    if (window.addEventListener) {
        return false;
    } else {
        return true;
    }
}
/**
 * 将对象转为url查询参数
 * @param {*} data
 * { "name": "Tom", "age": 23 }
 * -> name=Tom&age=23
 */
function encodeData(data) {
    if (!data) {
        return null;
    }
    let list = [];
    for (let [key, value] of Object.entries(data)) {
        list.push(`${key}=${value}`);
    }
    return list.join("&");
}
const CONTENT_TYPE = "Content-Type";
const contentTypeMap = {
    html: "text/html; charset=utf-8",
    xml: "text/xml; charset=utf-8",
    json: "application/json; charset=utf-8",
    form: "application/x-www-form-urlencoded"
}
/**
 *
 * @param {*} option:
 *   method
 *   url
 *   asyn
 *   type
 *   callback
 *   params
 *   data
 */
function ajax(option) {
    // 必传参数
    let url = option.url;
    let callback = option.callback;
    // 可选参数
    let method = option.method || "GET";
    let asyn = option.asyn || true;
    let params = option.params || {};
    let type = option.type || "html";
    let data = option.data || {};
    let xmlHttp = createXMLHttpRequest();
    // 处理响应数据
    xmlHttp.onreadystatechange = function () {
        // 双重判断 xmlHttp状态为服务器响应结束,服务器状态响应结束
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            // 获取响应结果
            let responseData = null;
            if (xmlHttp.responseXML) {
                responseData = xmlHttp.responseXML;
            }
            else {
                responseData = xmlHttp.responseText;
                try {
                    responseData = JSON.parse(responseData);
                } catch (e) {
                }
            }
            callback(responseData);
        }
    }
    // 处理请求数据
    if (params) {
        url = url + "?" + encodeData(params);
    }
    xmlHttp.open(method, url, asyn);
    xmlHttp.setRequestHeader(CONTENT_TYPE, contentTypeMap[type]);
    let sendData = null;
    if (type == "json") {
        sendData = JSON.stringify(data);
    } else {
        sendData = encodeData(data);
    }
    xmlHttp.send(sendData);
}
// console.log(encodeData(https://www.fons.com.cn/tag/undefined" target="_blank">undefined));