Shakespeare once said: “A good memory is worse than a bad pen.”
Chapter 1 Introduction to JavaScript
1.1 A brief history of JavaScript
1.2 JavaScript implementation
-
A complete JavaScript implementation should be composed of three different parts: core (ECMAScript), Document Object Model (DOM), and Browser Object Model (BOM).
-
ECMAScript: Provides core language functions; DOM: Provides methods and interfaces for accessing and operating web content; BOM: Provides methods and interfaces for interacting with browsers.
1.3 JavaScript version
Chapter 2 Using JavaScript in HTML
2.1 script element
-
Tag position: In order to avoid significant delays when the browser renders the page, modern web applications generally place all JavaScript references behind the page content in the element.
-
Delay script: The defer attribute indicates that the script will not affect the structure of the page when executed. The script will be delayed until the entire page is parsed before running; only applicable to external script files.
<script defer="defer" src="example.js"></script>
- Asynchronous script: The async attribute indicates that the current script does not have to wait for other scripts or block document rendering. It tells the browser to download the file immediately, and does not guarantee that scripts marked async will be executed in their order; it only applies to external script files.
<script async src="example1.js"></script>
<script async src="example2.js"></script>
2.2 Embedded code and external files
2.3 Document Mode
- Mixed mode and standard mode; turn on standard mode:
<!-- HTML 5 -->
<!DOCTYPE html>
2.4 noscript element
Chapter 3 Basic Concepts
3.1 Syntax
-
Case Sensitive: Everything in ECMAScript is case sensitive.
-
Strict mode: In strict mode, some undefined behaviors in ECMAScript 3 will be handled, and errors will be thrown for certain unsafe operations. Add the following code at the top:
"use strict";
3.2 Keywords and reserved words
3.3 Variables
- Assigning a value to an undeclared variable will cause a ReferenceError to be thrown in strict mode.
3.4 Data type
-
The typeof operator is used to detect the data type of variables.
-
5 simple data types: Undefined, Null, Boolean, Number, String; 1 complex data type (reference type): Object.
-
Undefined type: When a variable is declared using var but is not initialized, the value of the variable is undefined.
-
Null type: The null value represents a null object pointer; as long as the variable intended to save the object has not actually saved the object, the variable should be explicitly allowed to hold the null value.
-
Boolean type: To convert other types to Boolean type, use the function Boolean().
-Number type: Convert other types to Number type. Commonly used function parseInt(). When converting a string, if the first character is not a numeric character or a negative sign, NaN will be returned. The second parameter is optional and represents the base.
-
String type: Strings are immutable; to convert other types to String type, use the function toString() or String() or add an empty string (1+”).
-
Object type
How to create an object:
var o = new Object();
Create a custom object by creating an instance of the Object object and adding properties or methods to it;
The Object type is the basis for all its instances and has the following properties and methods:
-
constructor: retains the function used to create the current object, the constructor;
-
hasOwnProperty(propertyName): used to check whether the given property exists in the current object instance;
-
isPrototypeOf(object): used to check whether the incoming object is the prototype of the incoming object;
-
propertyIsEnumerable(); toLocaleString();
-
toString(): Returns the string representation of the object;
-
valueOf(): returns the string, numerical or Boolean representation of the object;
3.5 Operators
- When comparing strings, what is actually compared is the character encoding value of each character at the corresponding position in the two strings.
"23" < "3"; // true
-
When comparing a numerical value and a string, the string will be converted into a numerical value, and then compared numerically with another value; if it cannot be converted into a numerical value, it will be converted into NaN.
-
If any operand is compared with NaN, the result will be false.
NaN == NaN; // false
NaN === NaN; // false
NaN & gt;
NaN; // false
NaN & lt;
NaN; // false
- Equality (==) Congruence (===): Congruence only returns true if the two operands are equal without conversion.
"55" == 55; // true
"55" === 55; // false
- Conditional operators
variable = boolean_expression ? true_value : false_value;
3.6 Statement
- Since there is no block-level scope in ECMAScript, variables defined inside the loop can also be accessed externally:
for (var i = 0; i < 10; i++) {
var j = 1;
}
console.log(i, j); // 10 1
- The for-in statement can be used to enumerate the properties of an object.
for (property in expression) {
...
}
- The break and continue statements are used in conjunction with the label statement: This often occurs in nested loops.
var num = 0;
outermost:
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
if (i == 5 && j ==5) {
break outermost;
}
num++;
}
}
console.log(num); // 55
3.7 Function
- Function parameters: Parameters are represented internally by an array. What the function receives is always this array, regardless of which functions are contained in the array; this parameter array is accessed through the arguments object; named parameters only provide convenience, but are not required; the values in the arguments object are independent of the memory space of the corresponding named parameters, but their values will be synchronized.
function example(name, age) {
console.log("arguments:", arguments);
console.log("name:", name, "age:", age);
name = "DIYgod";
console.log(arguments[0]);
}
example("Anotherhome", "556", "www.anotherhome.net");
// arguments: ["Anotherhome", "556", "www.anotherhome.net"]
// name: Anotherhome age: 556
// DIYgod
Chapter 4 Variables, Scope and Memory Issues
4.1 Values of basic types and reference types
-
When operating an object, you are actually operating a reference to the object rather than the actual object.
-
When a basic type value is copied from one variable to another variable, a copy of the value is created; when a reference type value is copied from one variable to another variable, a pointer to an object stored in the heap is copied. After copying, the two variables point to the same object.
var o1 = {};
var o2 = o1;
o1.name = "DIYgod";
console.log(o2.name); // DIYgod
var n1 = 1;
var n2 = n1;
n1 = 2;
console.log(n2); // 1
- Pass parameters: Parameters can only be passed by value. When the parameter is an object, the same object is accessed inside the function.
function setName(o) {
o.name = "DIYgod";
o = {};
o.name = "Anotherhome";
}
var p = {};
setName(p);
console.log(p.name); // DIYgod
- To determine which basic type a value is, you can use the typeof operator, and to determine which reference type a value is, you can use the instanceof operator.
4.2 Execution environment and scope
-
The execution environment is divided into global execution environment and function execution environment; each execution environment has a variable object associated with it; every time you enter a new execution environment, a scope chain for searching for variables and functions will be created. The front end of the scope chain is the variable environment where the currently executed code is located, and the last object is the variable object of the global execution environment.
-
Query identifier: Start from the front end of the scope chain and search upwards step by step. The search results will stop when found. If not found, it will be traced back to the variable object of the global environment.
4.3 Garbage collection
-
The most commonly used garbage collection method is mark removal: the garbage collector will mark all variables stored in memory at runtime, and then remove the marks of variables in the environment and variables referenced by variables in the environment. After that, variables that are still marked are regarded as variables to be deleted, because these variables cannot be accessed.
-
Optimize memory usage: Only save necessary data for the executing code; once the data is no longer useful, it is best to release its reference by setting its value to null - dereference; the function of dereference is to take its value out of the execution environment so that the garbage collector can recycle it the next time it runs.
Chapter 5 Reference Types
5.1 Object type
- Create an Object instance: use the Object constructor; object literal.
// new 操作符法
var o1 = new Object();
o1.name = "DIYgod";
o1.age = 20;
// 对象字面量表示法
var o1 = {
name: "DIYgod",
age: 20,
};
- Access object properties: dot notation; square bracket notation. It is recommended to use dot notation.
// 点表示法
console.log(o.name);
// 方括号表示法
console.log(o['name']);
var n = 'name';
console.log(o[n]);
console.log(o['first name'];
5.2 Array type
- Create an array: use the Array constructor; use array literal notation.
var a1 = new Array();
var a2 = new Array(20);
var a3 = new Array("red", "blue", "green");
var a4 = [];
var a5 = ["red", "blue", "green"];
- Use length to add new items at the end.
var a = ["a", "b"];
a[a.length] = "c";
-
Detect array: Array.isArray() (solve the problem of incorrect instanceof detection result when there are more than two global execution environments).
-
Stack method and queue method: push() adds an item to the end of the array; pop() removes an item from the end of the array; shift() removes the first item of the array; unshift(); adds an item to the front of the array.
-
Reorder
-
reverse(): Reverse the order of array items.
-
sort(): By default, array items are converted into strings and then sorted in ascending order. Can receive a comparison function as a parameter.
The comparison function takes two parameters and returns a negative number if the first parameter is before the second parameter, 0 if they are equal, and a negative number if the second parameter is before the first parameter.
var a = [0, 1, 15, 10, 5];
a.sort();
console.log(a); // [0, 1, 10, 15, 5]
function compare(value1, value2) {
return value1 - value2;
}
a.sort(compare);
console.log(a); // [0, 1, 5, 10, 15]
- Operation method
- concat(): add items
var a1 = ["red", "green", "blue"];
var a2 = a1.concat("yellow", ["black", "brown"]);
console.log(a2); // ["red", "green", "blue", "yellow", "black", "brown"]
- slice(): intercept
var a = ["red", "green", "blue", "yellow", "black", "brown"];
console.log(a.slice(1), a.slice(1, 4)); // ["green", "blue", "yellow", "black", "brown"] ["green", "blue", "yellow"]
- splice(): delete, insert, replace
var a = ["red", "green", "blue", "yellow", "black", "brown"];
console.log(a.splice(2, 1), a); // 删除项; ["blue"] ["red", "green", "yellow", "black", "brown"]
console.log(a.splice(1, 0, "yellow", "orange"), a); // 插入项; [] ["red", "yellow", "orange", "green", "yellow", "black", "brown"]
console.log(a.splice(1, 1, "red", "purple"), a); // 替换项; ["yellow"] ["red", "red", "purple", "orange", "green", "yellow", "black", "brown"]
- Position method: indexOf() lastIndexOf() receives two parameters: the item to be found and (optional) the index of the starting point of the search; indexOf() searches from front to back, and lastIndexOf() searches from back to front; returns the position of the item to be searched, or -1 if not found.
var a = ["red", "purple", "orange", "green", "red", "yellow", "black", "brown"];
console.log(a.indexOf("red")); // 0
console.log(a.lastIndexOf("red")); // 4
console.log(a.indexOf("red", 1)); // 4
console.log(a.lastIndexOf("red", 1)); // 0
- Iteration method: every() some() filter() map() forEach().
var a = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var everyResult = a.every(function (item, index, array) {
return (item > 2);
});
console.log(everyResult); // false
var someResult = a.some(function (item, index, array) {
return (item > 2);
});
console.log(someResult); // true
var filterResult = a.filter(function (item, index, array) {
return (item > 2);
});
console.log(filterResult); // [3, 4, 5, 4, 3]
var mapResult = a.map(function (item, index, array) {
return (item * 2);
});
console.log(mapResult); // [2, 4, 6, 8, 10, 8, 6, 4, 2]
var forEachResult = a.forEach(function (item, index, array) {
console.log(item);
});
console.log(forEachResult); // undefined
- Merge method
var a = [1, 2, 3, 2, 1];
var sum1 = a.reduce(function (prev, cur, index, array) {
console.log(index); // 1 2 3 4
return prev + cur;
});
console.log(sum1); // 9
var sum2 = a.reduceRight(function (prev, cur, index, array) {
console.log(index); // 3 2 1 0
return prev + cur;
});
console.log(sum2); // 9
5.3 Date type
- Create a date object: the month is based on 0 (January is 0, February is 1…).
var d1 = new Date();
var d2 = new Date(2015, 2, 5, 17, 55, 55); // 2015年3月5日下午5点55分55秒
- Get the date, time and milliseconds when the call was made, which can be used to analyze the code.
var start = Date.now();
doSomething();
var stop = Date.now();
var result = stop - start;
- Date formatting method: local means displayed in a region-specific format.
var d2 = new Date(2015, 2, 5, 17, 55, 55);
d2.toString(); // "Thu Mar 05 2015 17:55:55 GMT+0800 (CST)"
d2.toDateString(); // "Thu Mar 05 2015"
d2.toTimeString(); // "17:55:55 GMT+0800 (CST)"
d2.toLocaleString(); // "2015/3/5 下午5:55:55"
d2.toLocaleDateString(); // "2015/3/5"
d2.toLocaleTimeString(); // "下午5:55:55"
5.4 RegExp type
- Create a regular expression:
The pattern part is a regular expression
Flags, flags, indicate the behavior of regular expressions: g global mode; i case-insensitive; m multi-line mode
var exp1 = / pattern / flags
var exp2 = new RegExp('pattern', 'flags');
- Instance methods:
- exec(): Returns an array of the first matching item information. The first item of the array is the string that matches the entire pattern, and the other items are strings that match the capturing groups in the pattern; it also contains two additional attributes, index and input.
var text = "I'm DIYgod, and this is Anotherhome";
var pattern = /and( this( is)?)?/gi;
var matches = pattern.exec(text);
console.log(matches.index); // 12
console.log(matches.input); // I'm DIYgod, and this is Anotherhome
console.log(matches[0]); // and this is
console.log(matches[1]); // this is
console.log(matches[2]); // is
- test(): Returns true if the pattern matches this parameter, otherwise returns false.
var text = "I'm DIYgod, and this is Anotherhome";
var pattern = /DIYgod/;
var matches = pattern.test(text);
console.log(matches); // true
- The RegExp constructor contains some attributes, which are applicable to all regular expressions in the scope and record some information about the latest regular expression operation.
5.5 Function type
- Define the function. The function is actually an instance of the Function type, so the function is also an object.
// 使用函数声明语法
function f1(n1, n2) {
return n1 + n2;
}
// 使用函数表达式
var f2 = function (n1, n2) {
return n1 + n2;
};
// 使用构造函数,不推荐
var f3 = new Function("n1", "n2", "return n1 + n2");
- The function name is a pointer to the function object.
function f1(n1, n2) {
return n1 + n2;
}
var f2 = f1;
f1 = null;
console.log(f2(1, 1)); // 2
-
There is no function overloading in ECMAScript.
-
The difference between function declaration and function expression: The interpreter will first read the function declaration and make it available before executing any code (function declaration promotion); the function expression must wait until the interpreter executes to the line where it is located before it is actually interpreted and executed.
console.log(f1(1, 1)); // 2
function f1(n1, n2) {
return n1 + n2;
}
console.log(f2(1, 1)); // Uncaught TypeError: f2 is not a function
var f2 = function (n1, n2) {
return n1 + n2;
};
- Function internal properties
- The callee attribute of the function’s arguments object: is a pointer pointing to the function that owns this arguments object. You can reduce the coupling between functions and function names during recursion.
<<<PROTECTED_BLOCK_35>>
- caller attribute: holds a reference to the function of the current function.
function outer() {
inner();
}
function inner() {
console.log(arguments.callee.caller); // function outer()...
}
outer();
- Function attributes and methods
- length attribute: Indicates the number of named parameters that the function hopes to receive.
function f(n1, n2) {
return n1 + n2;
}
console.log(f.length); // 2
- apply() call(): used to change the value of the this object of the function.
window.color = "red";
var o = {
color: "blue",
};
function sayColor(n1, n2) {
console.log(this.color);
return n1 + n2;
}
sayColor(1, 1); // red
o.sayColor = sayColor;
o.sayColor(); // blue
// 使用call和apply可以消除对象与方法的耦合关系
sayColor.call(window, 1, 1); // red
sayColor.call(o, 1, 1); // blue
sayColor.apply(window, [1, 1]); // red
sayColor.apply(o, [1, 1]); // blue
5.6 Basic packaging types
Boolean type, Number type, String type
Skip for now
5.7 Single built-in object
Global object, Math object
Skip for now
Chapter 6 Object-oriented Programming
6.1 Understanding objects
- Two properties: data properties and accessor properties. Characteristics: Various characteristics that describe attributes are used to implement the JavaScript engine and cannot be accessed directly.
- Data attributes, which have 4 characteristics:
-
[[Configurable]]: Indicates whether the attribute can be redefined by deleting the attribute through delete, whether the characteristics of the attribute can be modified, and whether the attribute can be modified into an accessor attribute.
-
[[Enumerable]]: Indicates whether the attribute can be returned through a for-in loop.
-
[[Writeable]]: Indicates whether the value of the attribute can be modified.
-
[[Value]]: Contains the data value of this attribute.
- Accessor properties, which have 4 properties:
-
[[Configurable]]: Indicates whether the attribute can be redefined by deleting the attribute through delete, whether the characteristics of the attribute can be modified, and whether the attribute can be modified into a data attribute.
-
[[Enumerable]]: Indicates whether the attribute can be returned through a for-in loop.
-
[[Get]]: Function called when reading properties.
-
[[Set]]: Function called when writing attributes.
- Define and read properties: Object.defineProperty() Object.defineProperties() Object.getOwnPropertyDescriptor()
6.2 Create objects
- Factory pattern: Although it solves the problem of creating multiple similar objects, it does not solve the problem of object recognition.
function createPerson(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function () {
console.log(this.name);
};
return o;
}
var p1 = createPerson("DIYgod", 20, "Software Engineer");
var p2 = createPerson("Anotherhome", 2, "Website");
- Constructor pattern. (Constructor should start with a capital letter)
<<<PROTECTED_BLOCK_40>>
This method goes through 4 steps:
-
Create a new object
-
Assign the scope of the constructor to the new object (this points to this new object)
-
Execute the code in the constructor (add properties to the new object)
-
Return new object
The problem with constructors: every method must be recreated on every instance.
console.log(p1.sayName === p2.sayName); // false
- Prototype pattern: Each function has a prototype property, which is a pointer pointing to an object (the prototype object of the function) that contains properties and methods that can be shared by all instances of the type.
// 组合使用构造函数模式与原型模式
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype.sayName = function () {
console.log(this.name);
};
var p1 = new Person("DIYgod", 20, "Software Engineer");
var p2 = new Person("Anotherhome", 2, "Website");
console.log(p1.sayName === p2.sayName); // true
- Understand prototype objects:
-
Whenever a new function is created, a prototype property is created for the function according to a specific set of rules, pointing to the prototype object
-
By default, all prototype objects will get a constructor property, pointing to the function where the prototype property is located
-
After calling the constructor to create a new instance, the instance will have a proto attribute pointing to the prototype object of the constructor. The pointer is called [[Prototype]], and the default prototype points to Object.
-
There is no direct relationship between instances and constructors
-
Read attributes: The search starts from the object instance itself. If not found, search for the prototype object
-
Use isPrototype() to detect whether there is a relationship between the constructor and the instance
-
Use hasOwnProperty() to detect whether the property exists in the instance or prototype
- Prototype and in operator
// in操作符会在通过对象能够访问到属性时返回true
console.log("name" in p1); // true
// 枚举属性
for (var prop in p1) {
console.log(prop); // name age job sayName
}
- Override prototype objects with object literals
function Person() {}
Person.prototype = {
constructor: Person, // 这里重写了prototype,不再默认有constructor属性
name: "DIYgod",
age: 20,
};
- Dynamic prototype pattern, parasitic constructor pattern, safe constructor pattern
6.3 Inheritance
- The most commonly used inheritance in JavaScript: combined inheritance. It combines the advantages of prototype chain and constructor.
function SuperType(name) {
this.name = name;
this.color = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function () {
console.log(this.name);
};
function SubType(name, age) {
SuperType.call(this, name); // 借用构造函数
this.age = age;
}
SubType.prototype = new SuperType(); // 原型链
SubType.prototype.constructor = SubType; // construcotr在上一句中被重写
SubType.prototype.sayAge = function () {
console.log(this.age);
};
var instance = new SubType("DIYgod", 20);
instance.sayName(); // DIYgod
instance.sayAge(); // 20
- Determine the relationship between prototypes and instances. Continuing from the previous example:
console.log(instance instanceof SuperType); // true
console.log(SuperType.prototype.isPrototypeOf(instance)); // true
- Prototypal inheritance, parasitic inheritance, parasitic combined inheritance
Chapter 7 Function Expressions
7.1 Recursion
7.2 Closure
-
A closure is a function that has access to variables in the scope of another function.
-
(See 4.2 for scope chain) The internal function defined inside the external function adds the active object containing the external function to its scope; after the external function is executed, its active object will not be destroyed, because the scope chain of the internal function still refers to the active object; after the external function is executed, the internal function can still access all the variables defined by it.
function outer() {
var name = "DIYgod";
return function () {
console.log(name);
};
}
var inner = outer();
inner(); // DIYgod
inner = null; // 解除对outer内部的匿名函数的引用,以便释放内存
- A closure can only obtain the last value of any variable in the containing function.
function createFunction () {
var result = [];
for (var i = 0; i < 10; i++) {
result[i] = function () {
return i;
}
}
return result;
}
console.log(createFunction()[0]()); // 10
console.log(createFunction()[1]()); // 10
// 返回的都是同一个变量i
- This of anonymous functions usually points to window.
var name = "The Window";
var object = {
name: "My Object",
getNameFunc: function () {
return function () {
return this.name;
};
},
};
console.log(object.getNameFunc()()); // The Window
7.3 Mimicking block-level scope
- Use anonymous functions to imitate block-level scope: the first bracket is used to convert the function declaration into a function expression (the function declaration cannot be called by adding brackets after it), and the second bracket is used to call the function.
(function () {
var i = 9;
console.log(i); // 9
})();
console.log(i); // Uncaught ReferenceError: i is not defined
7.4 Static objects
-
Any variable defined in a function can be considered a private variable.
-
Public methods that have access to private variables and private functions are called privileged methods.
function MyObject() {
// 私有变量和私有函数
var privateVariable = "DIYgod";
function privateFunction() {
console.log("lalala");
}
// 特权方法
this.publicMethod = function () {
console.log(privateVariable);
privateFunction();
};
}
var o = new MyObject();
o.publicMethod(); // DIYgod lalala
o.privateFunction(); // Uncaught TypeError: o.privateFunction is not a function
…
Chapter 13 Incident
13.1 Event flow
-
Event bubbling: The event is initially received by the most specific element, and then propagates upward to less specific nodes; IE9, FireFox, Chrome and Safari bubble the event all the way to the window object.
-
Event capture: Since older versions of browsers do not support it, few people use event capture.
-
The event flow specified by “DOM2-level events” includes three stages: event capture stage, target stage and event bubbling stage.
13.2 Event handler
- HTML event handler: Extend the scope. Within the function, you can access the document and members of the element itself like local variables. Example:
<input type="button" value="Click Me" onclick="alert(value)">
If it is a form input element, the scope will also contain the entrance to the form element, for example:
<form method="post">
<input type="text" name="username" value="">
<input type="button" value="Echo username" onclick="alert(username.value)">
</form>
Disadvantages: ① There is a time difference problem. Triggering the event before the parsing function will cause an error. ② The scope chain of the extended handler will lead to different results in different browsers. ③ Leading to tight coupling of HTML and JavaScript code.
- DOM0 level event handler
// 绑定事件处理程序
var btn = document.getElementById("myButton");
btn.onclick = function () {
console.log(this.id); // myButton
};
// 删除事件处理程序
btn.onclick = null;
Event handlers added in this way are processed during the bubbling phase of the event flow.
- DOM2 level event handler
addEventListener() and removeEventListener()
Three parameters: the name of the event to be processed, the function as the event handler, whether to call the function in the capture phase (true) or in the bubbling phase (false, default)
The advantage is that multiple event handlers can be added. Event handlers added using addEventListener can only be removed using removeEventListener, and anonymous functions cannot be removed.
- IE event handler
attachEvent() and detachEvent()
var btn = document.getElementById("myButton");
btn.attachEvent("onclick", function () {
console.log(this === window); // myButton
});
Event handlers added in this way are processed during the bubbling phase of the event flow.
13.3 Event Object
-
When an event on the DOM is triggered, an event object event is generated. This object contains all information related to the event. The event object only exists during the execution of the event handler. Once the event handler is completed, the event object is destroyed.
-
Properties/Methods:
currentTarget: the element that is handling the event
target: the target of the event
type: event type
cancelable: Default behavior that can prevent specific events
preventDefault(): prevent the default behavior of specific events
stopPropagation(): Stops the propagation of events in the DOM hierarchy, that is, cancels further event capturing or bubbling.
eventPhase: The stage of the event flow. The capture stage is 1, the target object is 2, and the bubbling stage is 3.
13.4 Event Type
- UI events, focus events, mouse events, wheel events, text events, keyboard events, synthesis events, and change events.
…
Chapter 21 Ajax and Comet
21.1 XMLHttpRequest object
- Usage
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readState === 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
console.log(xhr.responseText);
}
else {
console.log('Request was unsuccessful: ' + xhr.status);
}
}
};
xhr.open('get', 'example.php', true);
xhr.send(null);
-
Create XHR object: new XMLHttpRequest();
-
open(): starts a request to be sent; 3 parameters: request type, requested URL, and whether to send the request asynchronously (synchronization must wait until the server responds before continuing); the request will not actually be sent.
-
send(): Send request; 1 parameter: data to be sent; if no data is required to be sent, null must be passed in.
-
Properties of XHR objects:
-
responseText text returned
-
status HTTP status of the response.
- HTTP status code:
-
2xx success
-
3xx redirect, 304 Not Modified means that the requested resource has not been modified, and you can directly use the cached version in the browser, 302 Found means that the requested resource is now temporarily responding to the request from a different URI.
-
4xx client error, 403 Forbidden, 404 Not Found
-
5xx server error, 500 Internal Server Error, 503 Service Unavailable.
- readyState attribute of XHR:
-
0: not initialized
-
1: Start, open() has been called
-
2: Send, send() has been called
*3: Partial response data received
*4: All response data received
- readystatechange event: When the value of the readystate attribute changes from one value to another, the readystatechange event will be triggered.
21.4 Cross-domain resource sharing
-
CORS: Use custom HTTP headers to allow the browser to communicate with the server to determine whether the request or response should succeed or fail. XDR objects must be used in IE, and other browsers support XHR objects natively.
-
Image Ping: Only GET requests can be sent; the server’s response text cannot be accessed.
var img = new Image();
img.onload = img.onerror = function () {
console.log("Done!");
};
img.src = "http://api.hitokoto.us/rand?encode=jsc";
- JSONP: consists of two parts: callback function and data.
function myCallBack(data) {
console.log(data.hitokoto); // 像平常的你一样引发奇迹吧-
}
var script = document.createElement("script");
script.src = "http://api.hitokoto.us/rand?encode=jsc&fun=myCallBack"; // 返回一个包含在函数调用中的JSON,调用了myCallBack函数:myCallBack({"hitokoto":"...","author":"...",....});
document.body.insertBefore(script, document.body.firstChild);
Disadvantages: Security is unreliable; it is not easy to determine request failure.
To Be Continued…