4-14-17 JavaScript知识点总结(包括JOSN, ajax等,来源w3c)


JavaScript 

也称 ECMAScript as "JavaScript" 

 

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.

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,


 

Overviews:

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

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

JavaScript supports object-oriented programming. 

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

Js's types are :


 

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

OperatorDescription
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 :

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

Properties: 

PropertyDescription
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.再加上两个函数用于显示上下条数据。 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2018-04-14 09:18  Mr-chen  阅读(248)  评论(0编辑  收藏  举报