4-14-17 JavaScript知識點總結(包括JOSN, ajax等,來源w3c)


JavaScript javascript

也稱 ECMAScript as "JavaScript" php

 

It is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms機制 for communicating with the outside world. css

The most common host environment is the browser, but JavaScript interpreters(翻譯,解釋程序) can also be found in a huge list of other places, including Adobe Acrobat, Adobe Photoshop, SVG images, Yahoo's Widget engine, server-side environments such as Node.js, NoSQL databases like the open source Apache CouchDB,html


 

Overviews:前端

JavaScript is a dynamic language with types and operators, standard built-in objects, and methods.java

Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well. node

JavaScript supports object-oriented programming. web

JavaScript also supports functional programming — functions are objects, giving functions the capacity to hold executable code and be passed around like any other object.ajax

Js's types are :chrome


 

Numbers:

 

parseInt()至關於to_i 。 parseInt('123',10);// 123,第二個參數是轉換爲幾進制,默認10進制。相似的還有parseFloat()

 

特殊值: Infinity, -Infinity. 表明無窮數。  1/0// Infinity

isFinite(1/0);// false, 是有限的嗎?不是。

 


 

 

Strings 

'hello'.length;// 5

String像對象,可看成對象使用一些方法。 

'hello'.charAt(0); // "h"

 'hello, world'.replace('hello','goodbye'); // "goodbye,world"

 'hello'.toUpperCase(); // "HELLO"

 


 

othertypes 

 

  1. false, 0, empty strings (""), NaN, null, and undefined all become false.
  2. All other values become true.Boolean('');
  3. 例子Boolean('');// false
  4. Boolean(234);   // true

 

Variables

 

New variables in JavaScript are declared using one of three keywords: letconst, or var.

let allows you to declare block-level variables.只能在塊內用。

for (let myLetVariable = 0; myLetVariable < 5; myLetVariable++) {

   // myLetVariable is only visible in here  }

 

const 就是常量 const Pi =3.14;以後就不能改變了,不然報錯。Ruby是用所有大寫字母表示常量。

 

var 是變量,var name = ''tom"; 

 

 


 

 

 Operations:

 

和Ruby相似,+=,-= ,但多了 ++ ,—— 用法。

另外能夠這麼寫 :若是有字符串,就合併爲字符串。

'3'+4+5// "345" 

3+4+'5';  // "75"

  <><= and >=. 用於比較數字和字符串均可以。

== :      1 == true; //true 

===同時比較type: 1 === true; // false 

 

 

 


 

 

Control structures

 

if 

var name = 'kittens';

if (name == 'puppies') {

  name += ' woof';

} else if (name == 'kittens') {

  name += ' meow';

} else {

  name += '!';

}

name == 'kittens meow';

 

while和do..while

while (true) {

  // an infinite loop!

}

 

var input;

do {

  input = get_input();

} while (inputIsNotValid(input));

 

for循環3種。 

for (var i = 0; i < 5; i++) {
  // Will execute 5 times
}

JavaScript also contains two other prominent for loops: for...of

for (let value of array) {  
   // do something with value
} 

and for...in:

for (let property in object) { 
  // do something with object property 
}

 


 

 

Objects

JavaScript objects can be thought of as simple collections of name-value pairs. As such, they are similar to:  Hashes in Perl and Ruby.

"name" 是string類,value是任意類。兩種寫法:

var obj = new Object(); //相似Ruby  obj = Class.new()

And:

var obj = {};

var obj = {

  name: 'Carrot',
  details: {
    color: 'orange',
    size: 12
  }
};

Attribute access can be chained together:

很像obj.method,而且能夠用chain式寫法;也相似hash類的寫法。

obj.details.color; // orange 
obj['details']['size']; // 12
 

 

Function 特殊的object

相似Ruby中的類,其實js和Ruby都是everything is object.

function Person(name, age) {

  this.name = name;

  this.age = age;

}

// Define an object

var you = new Person('You', 24);

// We are creating a new person named "You" aged 24. 

 

obj.name = 'Simon';  等同於 obj["name"] = "Simon";用這種寫法✅好
var name = obj.name;

(後面還有Function的知識) 

 


 

 

Array也是特殊的對象

var a = new Array();  //相似Ruby, a = Array.new

a[0] = 'dog';

a[1] = 'cat';

a[2] = 'hen';

a.length; // 3   length是個方法

簡單寫法:

var a = ['dog', 'cat', 'hen']; // Ruby , a = ['dog', 'cat', 'hen']

a.length; // 3

 

 


 

Functions

Along with objects, functions are the core component in understanding JavaScript. The most basic function couldn't be much simpler:

function add(x, y) {
  var total = x + y; 
  return total;
} 

A JavaScript function can take 0 or more named parameters.

The function body can contain as many statements as you like and can declare its own variables which are local to that function.

The return statement can be used to return a value at any time. If no return statement is used (or an empty return with no value), JavaScript returns undefined.

 

add(); // NaN  // You can't perform addition on undefined 

 

You can also pass in more arguments than the function is expecting:多餘的參數被忽視掉 

add(2, 3, 4); // 5 // added the first two; 4 was ignored

 

例子1:

function avg() {

  var sum = 0;

  for (var i = 0, j = arguments.length; i < j; i++) {

    sum += arguments[i];

  }

  return{ sum / arguments.length };

}

add(2, 3, 4, 5); // 3.5

 

例子1的簡化寫法,例子2,使用rest parameter operator和for...of循環:

function avg(...args) {

  var sum = 0;

  for(let value of args) {

    sum += value;

  }

  return sum / args.length;

}

avg(2,3,4,5); //3.5 

 

例子2的 重寫法

function avgArray(arr) {

  var sum = 0;

  for(var i = 0, j = arr.length; i < j; i++) {

    sum += arr[i];

  }

  return sum / arr.length;

}

avgArray([2,3,4,5]);  // 3.5

 

javascript已經內置了avg(...numbers)方法

 


Custom objects

javasscript用函數做爲class ,也做爲方法。函數自己就是對象。

//相似一個類,能夠定義對象 

function makePerson(first, last) {

  return {

first: first, last: last

  };

}

//也相似一個方法 ,傳遞一個參數,返回結果。

function personFullName(person) {

  return person.first + ' ' + person.last;

}

function personFullNameReversed(person) {

  return person.last + ', ' + person.first;

}

//函數自己就是object 

s = makePerson('Simon', 'Willison');

personFullName(s); // "Simon Willison"

personFullNameReversed(s); // "Willison, Simon"

 

能夠用更好的寫法: 

function makePerson(first, last) {

  return {

first: first,

last: last,

fullName: function() {

  return this.first + ' ' + this.last;

        },

fullNameReversed: function() {

  return this.last + ', ' + this.first;

}

  };

}

s = makePerson('Simon', 'Willison');

s.fullName();   // "Simon Willison"

s.fullNameReversed(); // "Willison, Simon"

 the thiskeyword. Used inside a function, this refers to the current object. 

 this後面用.或[],便表示當前對象,若是沒有使用則是全局對象。 

 

new的寫法和this關鍵字來改進上面的寫法:去掉了return{};

function Person(first, last) {

  this.first = first;

  this.last = last;

  this.fullName = function() {

    return this.first + ' ' + this.last;

  };

  this.fullNameReversed = function() {

    return this.last + ', ' + this.first;

  };

}

var s = new Person('Simon', 'Willison');

new關鍵字代替了return。

Functions that are designed to be called by neware called constructor functions. 

 

可是,嵌套的函數寫法,尤爲是有好幾個函數,看起來很醜:改進:

function personFullName() {

  return this.first + ' ' + this.last;

}

function personFullNameReversed() {

  return this.last + ', ' + this.first;

}

function Person(first, last) {

  this.first = first;

  this.last = last;

  this.fullName = personFullName;

  this.fullNameReversed = personFullNameReversed;

}

看起來好多了,可是使用prototype方法,能夠隨時根據須要定義新的函數,更加方便:

function Person(first, last) {

  this.first = first;

  this.last = last;

}

Person.prototype.fullName = function() {

  return this.first + "" + this.last; 

}

Person.prototype.fullNameReversed = function() {

  return this.last + ", " + this.first;

相似於類的繼承,js裏面,若是聲明瞭一個string變量,使用String.prototype定義的方法,也能夠用在這個變量上。由於string對象繼承了String的方法。 

 

一樣,用prototype能夠從新定義js的內置方法。

《Ruby元編程2》--239覆寫方法:prepend,refinement細化,環繞別名。 

 

鑲嵌函數做用域,外部定義的變量,內函數能夠用,但內函數定義的變量,外面不能用。

 


 

 

Closures 

function makeAdder(a) {

  return function(b) {

    return a + b;

  };

}

var x = makeAdder(5);

var y = makeAdder(20);

x(6); // ?    11

y(7); // ?    27

 

解釋:

Whenever JavaScript executes a function, a 'scope' object is created to hold the local variables created within that function. It is initialized with any variables passed in as function parameters. 

只要傳進參數,函數初始化一個做用域對象,這個對象用來儲存全部在函數中建立的本地變量。

因此當makeAdder() 被調用時,一個scope obj就被建立了,裏面有一個property: a 。而後makAdder() 返回一個新建立的函數,這樣x裏面就儲存了a。

A Closure is the combination of a function and the scope object in which it was created. 閉包能夠儲存state,所以閉包經常被用來取代對象。

閉包的原理詳述(英文)https://stackoverflow.com/questions/111102/how-do-javascript-closures-work 

 



W3C.

Global Event Attributes

HTML 4 added the ability to let events trigger actions in a browser, like starting a JavaScript when a user clicks on an element.能夠把這些屬性加到html的元素中。

分幾大類:

 

  • window Event Attributes: <body>
  • Form Event: almost in all html element,但主要是用在form elements.
  • Keyboard Events: onkeydown
  • Mouse Events: onclick ,ondblclick, 9個屬性
  • Drag Event(8個屬性)
  • Clipboard Events : oncoyp, oncut, onpaste
  • Media Events:<audio> ,<img>,<video>等,但全部元素都能用。 

 

 


 JavaScript Can Change HTML Styless(css),Attributes, Content, Hide/Show

例子:

<!DOCTYPE html>
<html>
<body>
<p id="demo" style="display:none">Hello JavaScript!</p>

 

<button type="button" onclick="document.getElementById('demo').style.display='block'">Click Me!</button>
 
</body>
</html> 
 

JavaScript Functions and Events

A JavaScript function is a block of JavaScript code, that can be executed when "called" for.

For example, a function can be called when an event occurs, like when the user clicks a button.

 

JavaScript in <head> or <body>

Scripts can be placed in the <body>, or in the <head> section of an HTML page。也能夠放在 外部文件.js ; 用<script src="myScript1.js"></script>調用。能夠是部分url.

 


 

JavaScript Output

  • Writing into an HTML element, using innerHTML.
  • Writing into the HTML output using document.write().  should only be used for testing.
  • Writing into an alert box, using window.alert(). 彈出對話框
  • Writing into the browser console, using console.log() ,通常用於debugging. 好比在chrome-inspect的控制檯看js的輸出。

 


var x, y;          // How to declare variables
x = 5; y = 6;      // How to assign values

z = x + y;         // How to compute values

Js使用lower camel Case,首字母小寫的駝峯寫法。

 

Start the statement with var and separate the variables by comma:

var person = "John Doe", carName = "Volvo", price = 200;

 

var carName; //這個被聲明但沒有賦值,因此自動給一個值 undefined。

JS再聲明沒有任何效果。

var x = "5" + 2 + 3; //「523」

 

JavaScript Type Operators

Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type

 typeof {name:'John', age:34// Returns "object"

typeof [1,2,3,4]            

 // Returns "object" (not "array", see note below)

typeof null                  // Returns "object"

typeof function myFunc(){}   // Returns "function"

 

 

若是調用函數但沒有(),則返回函數定義自己。

若是調用函數,參數爲空,則返回NaN. (not a number)

判斷NaN 函數 isNaN(), NaN是一個數字, typeof Nan;  // returns "number"

 

JavaScript Function Scope

In JavaScript there are two types of scope:

  • Local scope
  • Global scope

JavaScript has function scope: Each function creates a new scope.

Scope determines the accessibility (visibility) of these variables.

Variables defined inside a function are not accessible (visible) from outside the function.

若是你分配一個值給一個未聲明的變量,這個變量自動成爲全局變量,最好別這麼用。

(Ruby 不須要聲明。 全局變量$name)

Function Arguments

Function arguments (parameters) work as local variables inside functions.

函數的參數被看做本地變量。


 

HTML Events

HTML元素身上發生的事情。 

An HTML event can be something the browser does, or something a user does.

  • An HTML web page has finished loading
  • An HTML input field was changed
  • An HTML button was clicked

HTML allows event handler attributeswith JavaScript code, to be added to HTML elements.

< element   event = ' some JavaScript ' >
 

<button onclick="document.getElementById('demo').innerHTML = Date()"> The time is? </button>

 <button onclick="this.innerHTML = Date()">The time is?</button>   //this關鍵字,改變本身。

 

 JS code 很長,通常event attribute用來調用function.

<button onclick="this.innerHTML = Date()"> The time is? </button>

 

What can JavaScript Do?

Event handlers can be used to handle, and verify, user input, user actions, and browser actions:

  • Things that should be done every time a page loads
  • Things that should be done when the page is closed
  • Action that should be performed when a user clicks a button
  • Content that should be verified when a user inputs data
  • And more ...

Many different methods can be used to let JavaScript work with events:

  • HTML event attributes can execute JavaScript code directly
  • HTML event attributes can call JavaScript functions
  • You can assign your own event handler functions to HTML elements
  • You can prevent events from being sent or being handled
  • And more ...

 

The Difference Between Arrays and Objects

In JavaScript, arrays use numbered indexes.  

In JavaScript, objects use named indexes.

判斷一個變量是否是Array類型。用 instanceof方法 :

var  fruits = [ "Banana" "Orange" "Apple" "Mango" ];
fruits  instanceof  Array      // returns true

 toString():把an array 變爲a string of array values(comma separated)

var  fruits = [ "Banana" "Orange" "Apple" "Mango" ];
document. getElementById ( "demo" ). innerHTML  = fruits. toString ();

//Banana,Orange,Apple,Mango
 

join(), pop(), push(), shift(),unshift()

concat()  method creates a new array by merging (concatenating) existing arrays:

slice(1):去掉第幾個元素。

sort():按照字母順序排序

reverse(), 反向排列元素 


break 和 continue 

The continue statement (with or without a label reference) can only be used to skip one loop iteration.

The break statement, without a label reference, can only be used to jump out of a loop or a switch.

With a label reference, the break statement can be used to jump out of any code block:

 var cars = ["BMW""Volvo""Saab""Ford"];

list: {
    text += cars[0] + "<br>"
    text += cars[1] + "<br>"
    text += cars[2] + "<br>"
    break list;  //直接跳出這個塊了。
    text += cars[3] + "<br>"
    text += cars[4] + "<br>"
    text += cars[5] + "<br>"
}

 

 


 

The constructor Property

The constructor property returns the constructor function for all JavaScript variables

false.constructor 

// Returns function Boolean() {[native code]}

[1,2,3,4].constructor             

// Returns function Array()   {[native code]}

{name:'John',age:34}.constructor  

// Returns function Object()  {[native code]}

new Date().constructor           

 // Returns function Date()    {[native code]}

function () {}.constructor        

// Returns function Function(){[native code]}

 


Js也有RegExp,和Ruby裏用法同樣,多了個test()方法

 


JavaScript Errors - Throw and Try to Catch

The try statement lets you test a block of code for errors (點擊連接,案例)

The catch statement lets you handle the errors.

The throw statement lets you create custom errors.

The finally statement lets you execute code, after try and catch , regardless of the result.

 try {

    Block of code to try
}
catch(err) {
    Block of code to handle errors

}

JavaScript Throws Errors(點擊連接,看案例)

When an error occurs, JavaScript will normally stop and generate an error message.

JavaScript will  throw an exception (throw an error).

JavaScript will actually create an Error object with two properties: name and message.

 

 

 

The finally Statement

 

The finally statement lets you execute code, after try and catch, regardless of the result:

 try {

  Block of code to try
}
catch(err) {
  Block of code to handle errors

finally {
  Block of code to be executed regardless of the try / catch result
}

 


JavaScript Debuggers

 

Debugging is not easy. But fortunately, all modern browsers have a built-in JavaScript debugger.

use console.log() to display JavaScript values in the debugger window

 debugger keyword stops the execution of JavaScript, and calls (if available) the debugging function.

在chrome的檢查器中自動會彈到debugger關鍵字。

 

 

 


 

Hoisting: lift sth up 

JavaScript Declarations are Hoisted

在用js編譯代碼的時候,先使用變量,而後再聲明變量是能夠的,由於js會默認把全部聲明放到當前script/function的頂部,執行的時候仍是先聲明後使用。 

不過(initialize)在聲明的同時賦值,如 :var x = 5; 則不會被hoist。

把Declare Variables 放到頂部是好的作法。

 


 

Style Guide 代碼規範

Always use 4 spaces for indentation of code blocks:

 

 

function toCelsius(fahrenheit) {

 

    return (5 / 9) * (fahrenheit - 32);
}

 



Avoid global variables,  avoid new,  avoid  ==,  avoid eval()

 The === operator forces comparison of values and type:用來代替==


 

 在js, 0表明false,

var x = 0;

if (x = 0)  //false

 


 

floats不會很是精確。

最好:arrays use numbered indexs; object use named indexs(👆提過)

 

 



 

JavaScript Forms

 


相關預習: 

 HTML Input Types: 

<input type="text"> defines a one-line text input field

<input type="password"> defines a password field

<input type="submit"> defines a button for submitting form data to a form-handler.

 

The form-handler is typically a server page with a script for processing input data.

The form-handler is specified in the form's action attribute:

<input type="submit"> defines a button for submitting form data to a form-handler.

 

<input type="reset"> defines a reset button that will reset all form values to their default values

<input type="radio"> defines a radio button.
<input type="checkbox"> defines a checkbox.

<input type="button" onclick="alert('hello')" value='Click me'> defines a button:

 

HTML5還定義了一堆其餘的類型: (都是前端,用C寫的須要新的瀏覽器支持。)

  • color  date datetime-local email  month week
  • number(輸入框只能輸入數字)  range  search
  • tel time  
  • url

HTML Input Attributes

The size attribute specifies the size (in characters) for the input field框:

The value attribute specifies the initial value for an input field:
he maxlength attribute specifies the maximum allowed length for the input field:(這個屬性不支持反饋feedback,必須提醒用戶)

 


JavaScript Form Validation

 

若是表格myForm的fname輸入框的值是空的,則提示消息。 

 function validateForm() {

    var x = document.forms["myForm"]["fname"].value;
    if (x == "") {
        alert("Name must be filled out");
        return false;
    }

}

表格在提交的時候調用JS function:

<form name="myForm" action="/action_page.php" 

   onsubmit="return validateForm()" method="post">

    Name: <input type="text" name="fname">
    <input type="submit" value="Submit">
</form>

 

HTML Constraint Validation

5 有了新的html驗證原理:約束性驗證,包含3部分:

 HTML Input Attributes

  • 如 disabled, max, required(輸入框不能空着),type, 
  • form(input屬性:在<form></form>外面加input元素,鎖定form的🆔),
  • formmethod(input屬性,第二個提交按鈕,必須手動增長post),
  • formaction(在input的屬性,定義提交的url) 

CSS Pseudo SelectorsA pseudo-class is used to define a special state of an element:如:20多個僞類

a.highlight:hover {
    color: #ff0000;

}

DOM Properties and Methods

須要配合HTML的約束,一塊兒使用。功能很是齊全的對輸入進行🚫。

Methods :

Property Description
checkValidity() Returns true if an input element contains valid data.
setCustomValidity() Sets the validationMessage property of an input element.

Properties: 

Property Description
validity Contains boolean properties related to the validity of an input element.
validationMessage Contains the message a browser will display when the validity is false.
willValidate Indicates if an input element will be validated.


還包括了 The validity property (Js的內置函數)of an input element contains a number of properties related to the validity of data(很是全面)

 


 Javascript HTML DOM EventLIstener

 

這個方法附加了一個對指定元素的event事件。

你能夠增長多個事件給一個元素。

你能夠增長多個相同類型的事件給一個元素。

這個方法默認是bubbing的,即嵌套的結構<div><p>..</p></div>:

      當兩個元素同時綁定了click事件,點擊了<P>會先激發它的event, 而後再激發<div>的event。

  也能夠選擇capture,即從外到內的捕捉event。

addEventListener() method,   removeEventListener()

結構:

element.addEventListener(event, function, useCapture);

useCapture是布林值,設置true就是capture觸發方式。

刪除事件監聽的實例: 點擊查看

 


 

DOM Nodes

用來區分一個頁面不一樣元素的助手:能夠配合getElementById, Class, TagName, querySelectorAll.

節點包括element,attribute,  text(就是實際內容)  , comment(就是註釋). 

All nodes in the node tree can be accessed by JavaScript. 

New nodes can be created, and all nodes can be nodified or deleted.

除了root節點,每一個節點都只有一個父節點, 能夠有不少子節點。

Siblings(brothers) are nodes with the same father.

 

DOM HTML tree 

 節點的導航:

 

  • parentNode
  • childNodes[nodenumber]
  • firstChild  等同於childNodes[0]
  • lastChild
  • nextSibling, previousSilbing 
 

等價關係: node.nodeValue 

document.getElementById("id02").innerHTML

等同於

document.getElementById("id01").firstChild.nodeValue

document.getElementById('id01').childNodes[0].nodeValue;

 

 

document.body能夠獲得<body>內的全部nodes

document.documentElement能夠得知所有的文檔,包括<head>, <body>

 


 

nodeName特性:(只讀)

元素的nodeName就是它的tag(字母大寫),好比<p>的nodeName是, <h1>的nodeName是 H1 

 

屬性節點的nodeName就是屬性名字。

text node的nodeName是#text

document node 的nodeName是#document

 


nodeValue特性

 

元素的nodeValue自定義

text node的nodeValue是它自己,

屬性的nodeName是屬性的value

 


nodeType特性 (只讀)

 

元素的nodeType都是 1 。

text node的nodeType是 3

 


使用節點對要操做的元素定位:增長,指定位置插入,移除,替換。

  • appendChild(this),
  • insertBefore(this, brother),
  • removeChild(this),
  • replaceChild(this, brother).

 

1.增長一個<p>: 要增長先要建立createElement('element')

  1. var para = document.createElement('p'); 
  2. var node = document.createTextNode('This is a new paragraph.');
  3. para.appendChild(node);
  4. 而後doucment.getElementById("XXid").appendChild(para);

 

2.指定位置插入:

father-element.insertBefore(this-element, sibling-element) 

在某個做爲父親的元素內部,插入一個元素,這個元素的位置依據它後面的兄弟元素判斷。

 <div id="div1">

<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var
 para = document.createElement("p");
var
 node = document.createTextNode("This is new.");
para.appendChild(node);

var
 element = document.getElementById("div1");
var
 child = document.getElementById("p1");
element.insertBefore(para, child);  //插在div內部的第一個位置。

</script>

 

3.刪除Removing Existing element(一些瀏覽器不支持)

 parent.removeChild(this-child)

 

4.替換 Replacing element

parent.replaceChild(this, sipling-child); 

 


JavaScript HTML DOM Collections

getElementsByTagName() method returns an HTMLCollection object.

使用length方法獲得集合中對象的數量,

能夠用循環對集合中的對象進行一一處理。(這不是array)

還有getElementsByClassName()

 


 

 

JavaScript HTML DOM Node LIsts

 

從一個document中提取的nodes的集合(list)。(點擊查看案例)

和NodeList Object功能相似:

querySelectorAll(), childNodes().

可使用length方法。可使用循環(這不是array)。

 

二者的區別(8,9):

  1. HTML DOM Collections是 元素的集合。
  2. NodeList是 文檔節點的集合。
  3. 二者用法基本同樣。很像。
  4. 它們的對象集合都很像Array,但不是array不能用array的方法。
  5. 都有length方法。
  6. 都提供[0, 1, 2, ...]來得到每一個子對象,相似array
  7. HTMCollections子對象可使用name, id, index number來存取。
  8. NodeList items只能用index number來存取。
  9. 只有NodeList 對象可以包含屬性節點和文本節點.

 


 

JavaScript JSON

JavaScript Object Notation

 

JSON is a format for storing and transporting data.

JSON is often used when data is sent from a server to a web page.

JSON format is text only, written with JS object notation

 

Why use JSON?

由於是test格式數據,容易被服務器傳輸和被任意編程語言儲存。

JSON.parse() and JSON.stringify()

因此,若是從一個服務器接收數據,用JSON格式,你能夠用它像其餘JS object同樣。 

 

JSON Syntax Rules(和js類似,js程序能夠輕鬆把JSON數據轉化爲js object)

 

  • Data is in name/value pairs:  "firstName":"John"  //必須加「」
  • Curly braces hold objects:{"firstName":"John""lastName":"Doe"}
  • Square brackets hold arrays:
"employees" :[
     { "firstName" : "John" "lastName" : "Doe" }, 
     { "firstName" : "Anna" "lastName" : "Smith" }, 
     { "firstName" : "Peter" "lastName" : "Jones" }
]

 

Converting a JSON Text to a JavaScript Object

一個常常的使用json的地方是從web服務器讀取數據而後在網頁顯示數據:

 

  1. create a JS string containing JSON syntax;
  2. use JSON.parse() to convert the string into a JS object;
  3. use the new JS object in your page;

 

Sending Data: JSON.stringify()

數據庫中的JavaScript object -> 轉化爲JSON的text數據格式 ->發送給a server 

 

Receiving Data:JSON.parse()

接收到JSON 格式的data(就是字符串),->轉化爲JavaScript Object 

 

Storing Data and Retrieving Data: 

儲存:localStorage.setItem("要儲存的數據的名字", myJSON); 

取出:localStorage.getItem("要取出的數據的名字") 

 

JSon vs XML https://www.w3schools.com/js/js_json_xml.asp

 XML用起來更麻煩,轉化爲JS也麻煩。JSON轉化更快。

對於AJAX applications, JSON is faster and easier than XML:

 

JSON 的 value只能是string ,number, boolean, null, array, 和 an object(JSON object) ,不能是函數和undefined;

 


 JSON From the Server

只要服務器端的response是用JSON格式寫的,就能夠用JSON.parse轉化爲a JS object. 

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {

   if (this.readyState == 4 && this.status == 200) {

     var myObj = JSON.parse(this.responseText);

     document.getElementById("demo").innerHTML = myObj.name; 

  }

}; 

xmlhttp.open("GET", "json_demo.txt", true);  // 也能夠是php文件:"demo_file.php"

xmlhttp.send(); 

 


知識點很全的案例: 

 https://www.w3schools.com/js/tryit.asp?filename=tryjson_html_table_dynamic

 

 

 

 


 


AJAX - The XMLHttpRequest Object

 

The Keystone of AJAX is the XMLHttpRequest Object(關鍵之石,中文擎天博玉柱的意思) 

用於在後臺和服務器交互數據,意味着局部加載網頁,而不是reload整個頁面。 

 variable new XMLHttpRequest();

 

The XMLHttpRequest() Object又8個方法,6個properties.

 

6個 properties: 

 

  1. onreadystatechange: defines a function to be called when the readyState property changes. 這是一個內置函數。
  2. readyState: 從名字就能看出是property。有5個XMLHttpRequest狀態。
    • 4: request finished and response is ready, 請求完成,等待反饋接收。
    • 2: request received.
    3. responseText: Returns the response data as a string.

    4. responseXML: Returns the response data as XML data.

    5. status:     Returns the status-number of a request.(所有狀態碼信息),這是一系列的數字,用來表示web server 和 browser之間的交互狀況。

 

  •  200:  'ok' 標準的反饋,你的請求已經處理成功!
  •  403: "Forbidden", 請求收到,可是拒絕給你反饋。
  •  404: "Not Found"  ,服務器告訴瀏覽器請求還沒收到。

 

 

 8個 methods:

 

  1. 新建:new XMLHttpRequest()
  2. 中斷: abort(),中止當前請求
  3. getAllResponseHeaders():  Returns header information
  4. getResponseHeader():  Returns specific header information 
  5. open(method, url, async, user, psw): 指定請求格式。
    • method: the request type:  GET/POST
    • url: the file location (請求發送的地址)
    • async: true/false 同步或者異步
    • user 和 psw 是可選項.
  6. send():  發出的指令(發射!)。type is GET
  7. send(string): 發出的指令, 請求類型是POST
  8. setRequestHeader(header, value):   Adds a label/value pair to the header to be sent.  header是名字,value是值。

 


實例:

function loadDoc() {

 創建請求對象: 

  var xhttp = new XMLHttpRequest();

 用onreadystatechange定義一個函數: 若是請求收到服務器的一個回答,則執行函數 (請求對象等待服務器處理請求)

  xhttp.onreadystatechange = function() {

 若是readyState是4(請求完成而且反饋也傳回了)而且status是200(http反饋的詳細信息用數字進行區分,這裏是反饋給瀏覽器請求成功了)則。。。 

    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };

 設置請求對象的請求格式,是獲取信息仍是傳輸更新的信息, 鏈接到url(文件),同步/異步

 通常是異步true, 這樣JS不須要等待回覆,先執行其餘scripts

  xhttp.open("POST", "ajax_info.txt", true);

 設定更新數據的頭部, 

   xhttp.setRequestHeader("Content-type", "application/x-www-form-  urlencoded"); 

 口令:發射! 

  xhttp.send("fname-Henry&lname=Ford");
}

 


AJAX - Server Response

The onreadystatechange Property:

用於定義一個等待執行的函數 。每當readyState特性變化時,這個函數就執行一次。

由於readyState從1-4變化四次,因此函數總共執行4次,

readyState: Holds the status of the XMLHttpRequest. 表示請求處理的狀況,5個步驟。

    0. request not initialized 

 

  1. server connection established
  2. request received
  3. processing request
  4. request finished and response is ready 

 

status property: Holds the status of the object. 表示服務器處理請求對象的結果狀態。用數字表示。信息100-103,成功200-206,Redirection:300-308, Client Error:400-417,  Server Error 500-511.

 


The getAllResponseHeaders() Method

 從服務器返回全部的頭部信息,如length, server-type, content-type, last-modified等10幾種。

 

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML =
    this.getAllResponseHeaders();
  }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

 

The getResponseHeader() Method返回指定的頭部信息

var xhttp = new XMLHttpRequest();
document.getElementById("demo").innerHTML =
    this.getResponseHeader("Last-Modified");

 


一個時候xml和jS 的例子:AJAX XML Example

https://www.w3schools.com/js/js_ajax_xmlfile.asp 

https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_xml2 

數據的獲取是調用請求對象的特性responseXML,而後使用getElementByTagName和DOM 的node節點得到想要顯示到瀏覽器頁面的數據。

 

  1. 點擊按鈕,loadDoc()函數被執行。(加載文檔函數 )
  2. loadDoc()建立一個XMLHttpRequest對象,增長一個函數myFunction(),這個函數在收到服務器的反饋後執行。
  3. 當收到服務器反饋後,創建一個HTML table, 從XML file中提取node的數據,而後把這個table和XML data更新到瀏覽器頁面的對應getElementById()的位置

 

 https://www.w3schools.com/js/cd_catalog.xml

 


AJAX能夠和php,asp應用交互,能夠和數據庫交互。



集合XML, HTTP,DOM, JS的實例。

1. 顯示整個表格

2. 顯示其中一組數據

3.再加上兩個函數用於顯示上下條數據。 

相關文章
相關標籤/搜索