Java rookie supply station---AJAX and JSON

table of Contents

JSON

JSON (JavaScript Object Notation, JS Object Notation)

Same as XML

Difference from XML

Why use JSON?

Why is JSON better than XML?

JSON syntax

JSON syntax rules

JSON name/value pairs

JSON value

JSON number

JSON object

JSON array

JSON boolean

JSON null

JSON uses JavaScript syntax

Instance

JSON object

Object syntax

Instance

JSON array

Array as JSON object

Array in JSON object

There are three data formats for json objects

AJAX

AJAX request method

AJAX request in jQuery

$.ajax method

 $.get()

$.post()

How AJAX works

AJAX is based on existing Internet standards

AJAX instance analysis


JSON

JSON (JavaScript Object Notation, JS Object Notation)

JSON (JavaScript Object Notation, JS object notation) is a lightweight data exchange format that is easy to read and write, and easy to parse and generate by machine. JSON uses a completely language-independent text format. Many languages ​​provide support for JSON, so JSON is an excellent data exchange (between client and server) language.

It is based on a subset of ECMAScript and uses a text format completely independent of the programming language to store and represent data. The concise and clear hierarchical structure makes JSON an ideal data exchange language. It is easy for people to read and write, but also easy for machine to parse and generate, and effectively improve the efficiency of network transmission.

The JSON:  J AVA S cript  O bject  N otation (the JavaScript Object Notation)

JSON is a grammar for storing and exchanging textual information. Similar to XML.

JSON is smaller, faster, and easier to parse than XML.

Same as XML

  • JSON is plain text
  • JSON is "self-descriptive" (human readable)
  • JSON has a hierarchical structure (there is a value in the value)
  • JSON can be parsed by JavaScript
  • JSON data can be transmitted using AJAX

Difference from XML

  • No closing tag
  • Shorter
  • Faster reading and writing
  • Able to use the built-in JavaScript eval() method for parsing
  • Use array
  • Do not use reserved words

Why use JSON?

For AJAX applications, JSON is faster and easier to use than XML:

Use XML

  • Read the XML document
  • Use XML DOM to loop through the document
  • Read the value and store it in a variable

Use JSON

  • Read JSON string
  • Use eval() to process JSON strings

Why is JSON better than XML?

XML is more difficult to parse than JSON.

JSON can be parsed directly using existing JavaScript objects.

For AJAX applications, JSON is faster and simpler than XML data loading:

Use XML

  • Get the XML document
  • Use XML DOM to iterate through documents
  • Parse the data and copy it to the variable

Use JSON

  • Get JSON string
  • JSON.Parse parses JSON strings

JSON syntax

JSON syntax is a subset of JavaScript syntax.

JSON syntax rules

JSON syntax is a subset of JavaScript object representation syntax.

  • Data is in name/value pairs
  • Data is separated by comma
  • Curly braces save objects
  • Brackets save the array

JSON name/value pairs

The writing format of JSON data is: name/value pairs.

The name/value pair includes the field name (in double quotes), followed by a colon, and then the value:

"name" : "程序猿"

This is easy to understand and is equivalent to this JavaScript statement:

name = "程序猿"

JSON value

The JSON value can be:

  • Number (integer or floating point)
  • String (in double quotes)
  • Logical value (true or false)
  • Array (in square brackets)
  • Object (in braces)
  • null

JSON number

JSON numbers can be integer or floating point:

{ "age":30 }

JSON object

The JSON object is written in braces ({}):

Objects can contain multiple name/value pairs:

{ "name":"程序猿" , "url":"www.runoob.com" }

This is also easy to understand and is equivalent to this JavaScript statement:

name = "程序猿" url = "www.runoob.com"

JSON array

The JSON array is written in square brackets:

The array can contain multiple objects:

{ "sites": [ { "name":"程序猿" , "url":"www.runoob.com" },
{ "name":"google" , "url":"www.google.com" },
 { "name":"微博" , "url":"www.weibo.com" } ] }

In the above example, the object "sites" is an array containing three objects. Each object represents a record about a certain website (name, url).

JSON boolean

JSON boolean values ​​can be true or false:

{ "flag":true }

JSON null

JSON can set a null value:

{ "runoob":null }

JSON uses JavaScript syntax

Because JSON uses JavaScript syntax, it can process JSON in JavaScript without additional software.

With JavaScript, you can create an array of objects and assign values ​​like this:

Instance

var sites = [ { "name":"runoob" , "url":"www.runoob.com" },
 { "name":"google" , "url":"www.google.com" }, 
{ "name":"微博" , "url":"www.weibo.com" } ];

The first item in the JavaScript object array can be accessed like this (the index starts at 0):

sites[0].name;

The content returned is:

runoob

You can modify the data like this:

sites[0].name="程序猿";

JSON object

Object syntax

Instance

{ "name":"runoob", "alexa":10000, "site":null }

JSON objects are written in braces ({}).

Objects can contain multiple  key/value (key/value) pairs.

The key must be a string, and the value can be a valid JSON data type (string, number, object, array, boolean or null).

Use colon (:) to separate key and value.

Each key/value pair is separated by a comma (,).

JSON array

Array as JSON object

Instance

[ "Google", "Runoob", "Taobao" ]

The JSON array is written in square brackets.

The array value in JSON must be a valid JSON data type (string, number, object, array, boolean or null).

In JavaScript, array values ​​can be the above JSON data types, or JavaScript expressions, including functions, dates, and  undefined .

Array in JSON object

The value of an object property can be an array:

Instance

{ "name":"网站", "num":3, "sites":[ "Google", "Runoob", "Taobao" ] }

 

There are three data formats for json objects

They are as follows:

Types of grammar Explanation
Object type {name:value,name:value...} Where name is a string type, and value is any type
Array/collection type [value,value,value...]或[{},{}... ...] Where value is any type (such as js object, or array)
Mixed type {name:[]... ...} Properly wrap nested object types and array types

json data format: mainly composed of object {} and array []:

The objects include key-value pairs (attribute: attribute value) {key: value}, and the value can be str, num, list, obj. Use objcet.key for value

{key: value, key2:value2,} key: values ​​are separated by colons, used between pairs, and connected

The array contains elements: num, str, list, objcet are all available, use index to access [index], and use. To connect each value:

var stu = {"student":           //stu 对象包含student的key,值为一个数组
[                                     //数组的每一个值为一个具体的学生对象
{"name": "Tom","Grade":1, "age":11, "gender": "M"},     //学生对象的键为名字,值为对应属性
{"name": "Jerry", "Grade":1, "age":10, "gender": "M"}       //每个属性对应的是一个key,value对
],
"classroom": {"class1": "room1", "class2": "room2"}         //对象的值,嵌套对象
};

Read data:

document.write(stu.student[1].name);     // 输出第二个学生名
document.write(stu.student[0].age);      // 输出第一个学生年龄
document.write(stu.classroom.class1);    // 输出 classroom 的 class1 值
document.write(stu["classroom"].class2); // 也可用中括号键访问对象值

AJAX

AJAX stands for "Asynchronous JavaScript And XML" (asynchronous JavaScript and XML). It refers to a web development technology for creating interactive web applications. By exchanging a small amount of data with the server in the background, Ajax can enable web pages to be updated asynchronously. This means that certain parts of the webpage can be updated without reloading the entire webpage. Traditional web pages (not using Ajax) must reload the entire web page if the content needs to be updated.

AJAX is a browser that initiates a request asynchronously through js. Technology to update the page partially.

AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML).

AJAX is not a new programming language, but a new way of using existing standards.

The biggest advantage of AJAX is that it can exchange data with the server and update part of the web page content without reloading the entire page.

AJAX does not require any browser plug-ins, but requires users to allow JavaScript to execute on the browser.

Synchronization: The client must wait for the server to respond. No other operations can be performed during the waiting period

Asynchronous: No server-side response is required

Ajax can update part of the webpage without loading the webpage

AJAX引擎会在不刷新浏览器地址栏的情况下,发送异步请求

1.1 使用JavaScript获得浏览器内置的AJAX引擎(XMLHttpRequest对象)

1.2 使用js确定请求路径和请求参数

1.3  AJAX引擎对象根据请求路径和请求参数进行发送请求

服务器接收到ajax引擎的请求进行处理

2.1     服务器获得请求参数数据

2.2     服务器处理请求业务(调用业务层代码)

2.3     服务器响应数据给ajax引擎

AJAX引擎获得服务器响应的数据,通过执行JavaScript的回调函数将数据更新到浏览器页面具体位置。

3.1     通过设置给AJAX引擎的回调函数获得服务器响应的数据

3.2     使用JavaScript在指定的位置,显示响应数据,从而局部修改页面的数据,达到局部刷新目的。

 

AJAX request method

Attribute name Explanation
url The requested server-side url address
async (Default: true) By default, all requests are asynchronous requests. If you need to send a synchronization request, please set this option to false
data The data sent to the server can be in the form of key-value pairs or in the form of js objects
type (Default: "GET") Request method ("POST" or "GET"), the default is "GET"
dataType The expected return data type, the value can be xml, html, script, json, text, _defaul, etc.
success Callback function after successful request
error Call this function when the request fails

AJAX request in jQuery

$.ajax({key:value,key:value})

$.ajax method

  • url represents the request address
  • type indicates the request type GET/POST
  • data represents the data sent to the server
  • name = value & name = value
  • {key:value}
  • success request response, response callback function
  • dataType response data type

 $.get()

  • url
  • data
  • callback
  • type

$.post()

  • url
  • data
  • callback
  • type

How AJAX works

 

 

 

 

 

 

 

 

AJAX is based on existing Internet standards

AJAX is based on existing Internet standards and uses them jointly:

  • XMLHttpRequest object (asynchronously exchange data with the server)
  • JavaScript/DOM (information display/interaction)
  • CSS (define styles for data)
  • XML (as the format of the converted data)

AJAX instance analysis

        $.ajax({
              url:'/api/v1/questions/hits',
              type:'get',
              dataType:'json',
              success:function (json) {
                  questionApp.questions = json.data;
              }
           });
Vue.component('v-select', VueSelect.VueSelect);
let createQuestionApp = new Vue({
    el: '#createQuestionApp',
    data: {
        title: null,
        tags: [],
        selectedTagIds: [],
        teachers: [],
        selectedTeacherIds: []
    },
    methods: {
        loadTags: function () {
            $.ajax({
                url: '/api/v1/tags',
                type: 'get',
                success: function (json) {
                    let tags = [];
                    for (let i = 0; i < json.data.length; i++) {
                        let op = {
                            label: json.data[i].name,
                            value: json.data[i].id
                        };
                        tags[i] = op;
                    }
                    createQuestionApp.tags = tags;
                }
            });
        },
        loadTeachers: function () {
            $.ajax({
                url: '/api/v1/users/teacher/list',
                type: 'get',
                success: function (json) {
                    let teachers = [];
                    for (let i = 0; i < json.data.length; i++) {
                        let teacher = {
                            label: json.data[i].nickname,
                            value: json.data[i].id
                        }
                        teachers[i] = teacher;
                    }
                    createQuestionApp.teachers = teachers;
                }
            });
        },
        createQuestion: function () {
            let content = $('#summernote').val();
            console.log("标题:" + this.title);
            console.log("选中的标签:" + this.selectedTagIds);
            console.log("选中的老师:" + this.selectedTeacherIds);
            console.log("正文:" + content);

            $.ajax({
                url:'/api/v1/questions/create',
                type:'post',
                traditional:true,
                data:{
                    title:createQuestionApp.title,
                    tagIds:createQuestionApp.selectedTagIds,
                    teacherIds:createQuestionApp.selectedTeacherIds,
                    content:content
                },

                success:function (json) {
                    if (json.state==2000){
                        alert("发表问题成功!!!")
                    }else{
                        alert(json.message);
                    }
                }
            });
        }
    },
    created: function () {
        this.loadTags();
        this.loadTeachers();
    }
});

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/c202003/article/details/107548406