Ajax+node.js Front-end Interaction Best Practices (06)

Source: Internet
Author: User
Tags readfile try catch

6.XMLHttpRequest objects

XMLHttpRequest is an API that provides the client with the ability to transfer data between the client and the server. It provides a simple way to get data through a URL and does not refresh the entire page. This allows the page to update only a subset of the pages without disturbing the user. XMLHttpRequest is used extensively in AJAX.

6.1. Creating XMLHttpRequest Objects 6.1.1 XMLHttpRequest compatibility issues

XMLHttpRequest in IE6 below is used in the form of plug-ins, is not built into the browser, so under the IE6 can not be used in the form of new XMLHttpRequest, under IE through the new Activeobject (" Microsoft.XMLHTTP ") to use, therefore, can be written like this:

var xhr = null; if (window. XMLHttpRequest) {//Standard mode    XHR = new XMLHttpRequest ();} ELSE{//IE6 below walk here    xhr = new ActiveXObject (' Microsoft.XMLHTTP ');}

  

Compatibility is also handled in many places through the form of exception handling. try...catch...finally statement Syntax structure:

try{    //Try to execute this code if it is wrong to execute the code inside the catch}catch (e) {    //try inside the error message will be stored in the parameter e}finally{    //Whether or not the wrong end will execute this code Usually it is not written here just  a combination of Try Catch}try{    SDFs;    Alert (1);} catch (e) {    alert (2);} finally{    alert (3)}//execution Results first 2 reload 3   try inside the statement error

  

Ajax Object Compatibility notation:

var xhr = null, try{//standard does not error execution here code    XHR = new XMLHttpRequest ();} catch (E) {    ed//ie the statement in the next try error executes the code here}

  

6.2.open method

The Open method is similar to the form submission data

表单提交数据:    action: 数据提交的地址,如果不写,默认提交到当前页面    method: 数据提交的方式,有get和post两种方式,默认使用get方式,url长度有限制,所以不要通过    get方式传递过长的数据,post方式理论上没有长度限制,但是可以通过修改配置文件设置长度    enctype: 提交数据的格式,默认提交数据格式为:enctype="application/x-www-form-urlencoded"

Open method Syntax:

xhr.open("get","01.txt",true);xhr为创建好的ajax对象第一个参数: 打开方式,这里的打开方式跟表单差不多,有get和post两种方式,相当于method第二个参数: 打开的地址,这里就相当于表单里的acthion属性第三个参数: 是否异步 同步:阻塞模式,当前一条代码会影响后面代码执行 异步:非阻塞模式,前面的 代码不会影响后面代码的执行
6.3. Sending and retrieving data

Send data via the Send method to get the data by listening to the ReadyStateChange event

Send request----> equivalent to click the ENTER key to send the process    xhr.send ();    Monitor request Status---> Wait for return data after sending, the website shows    xhr.onreadystatechange = function () {        if (xhr.readystate = = 4 && Xhr.status = =) {            alert (xhr.responsetext);        }    }

  

ResponseText: The data returned by the server is stored in one of the responsetext properties of the Ajax object ReadyState: Represents the working state of Ajax, a total of 5 states

            状态0: 表示ajax对象创建成功(初始化),但是还没有调用open方法            状态1:表示已调用send方法,正在发送数据(载入数据)            状态2:send方法发送完成,已经收到响应内容(载入完成)            状态3:表示正在解析内容(解析)(注:收到响应内容后,还需要解析内容)            状态4:响应内容解析完成,可以使用数据了(注:状态为4的时候说明所有流程已经完成,拿到数据了)

Onreadystatechang: This event is used to listen to the AJAX working state and may be triggered more than once, indicating that it is triggered when the state has changed

Status: Indicates the state code of the server

With the understanding of the above properties, the fault-tolerant processing of Ajax when acquiring data can be written like this:

Xhr.onreadystatechange = function () {    if (xhr.readystate = = 4) {        if (xhr.status = =) {            alert ( Xhr.responsetext);        } else{            Alert ("Error:" +xhr.status);}}}    

  

6.4. Processing with data conditions

The Get method sends the data, the data is sent in the URL address in the past, in the Ajax also through this form of data transmission

Create an Ajax object----> equivalent to open the browser    var xhr = new XMLHttpRequest ();    Open the address where you want to get the file----> equivalent to the input URL    xhr.open (' Get ', '/getdata?username=xiaoqiang&age=19 ', true);    Send request----> equivalent to click the ENTER key to send the process    xhr.send ();    Monitor request Status---> Wait for return data after sending, the website shows    xhr.onreadystatechange = function () {        if (xhr.readystate = = 4 && Xhr.status = =) {            alert (xhr.responsetext);        }    }

  

Note: Send request by Get mode in IE will appear two problems, the first is the cache problem second is the garbled problem, need to pass encodeURI () for transcoding to send

The Post method sends the request data, the data is sent in the request body inside the past, in Ajax, the data is placed in the Send method in the past, and to set the type of the request header

Create an Ajax object----> equivalent to open the browser    var xhr = new XMLHttpRequest ();    Open the address where you want to get the file----> equivalent to the input URL    xhr.open (' Post ', '/getdata ', true);    Send request----> equivalent to click the ENTER key to send the process    xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");    Xhr.send (' username=xiaoqiang&age=19 ');    Monitor request Status---> Wait for return data after sending, the website shows    xhr.onreadystatechange = function () {        if (xhr.readystate = = 4 && Xhr.status = =) {            alert (xhr.responsetext);        }    }

  

For a chestnut: 1 Ajax Edition User login authentication

login.html File Contents

<!    DOCTYPE html>

  

Code in server-side index.js

var http = require (' http '); var url = require (' URL '); var fs = require (' FS '); var querystring = require (' querystring '); var ap  p = http.createserver (function (req, res) {res.setheader (' content-type ', ' text/html;charset=utf-8 ');  var url_obj = Url.parse (Req.url); if (url_obj.pathname = = = '/login ' && req.method=== ' GET ') {fs.readfile ('./login.html ', ' utf-8 ', function (err, DA        TA) {if (!err) {res.write (data);      Res.end ();    }})}//Processing Ajax Request if (url_obj.pathname = = = '/login ' && req.method = = = ' POST ') {console.log (1);    var post_data = ';    Req.on (' Data ', function (chunk) {post_data + = chunk;    });       Req.on (' End ', function () {var post_obj = Querystring.parse (Post_data); if (post_obj.username = = = ' Admin ' && post_obj.password = = = ' 123456 ') {res.write (' {' status ': 0, ' message ': ' Login       Success "}");       }else{res.write (' {' Status ': 1, ' message ': ' Username or password error '} ');    } res.end (); })}); App.listen (3000);

  

2 Getting background data

<!        DOCTYPE html>

  

App.js Code:

var http = require (' http '), var url = require (' URL '), var fs = require (' FS '), var app = Http.createserver (function (req, res) {  res.setheader (' Content-type ', ' text/html;charset=utf-8 ');  var url_obj = Url.parse (req.url);  if (url_obj.pathname = = =/') {    fs.readfile ('./index.html ', ' utf-8 ', function (err, data) {      if (!err) {        Res.write (data);        Res.end ();}}    )  }  Processing AJAX Requests  if (url_obj.pathname = = = '/getdata ') {    var arr = ' [' + '        {' title ': ' XI attended the National Science and Technology Award Conference 1 ', ' Time ': ' +new date (). tolocaledatestring () + ' "}, ' +        ' {" title ":" Xi attended the National Science and Technology Award Conference 2 "," Time ":" ' +new Date ". toLocaleDateString () + ' "}, ' +        ' {" title ":" Xi attended the National Science and Technology Award Conference 3 "," Time ":" ' +new Date (). tolocaledatestring () + ' "}, ' +        ' {' "title": "Xi attended the National Science and Technology Award Conference 4", "Time": "' +new Date ()." toLocaleDateString () + ' "} ' +        '];    Res.write (arr);    Res.end ();  }}); App.listen (3000);

  

Ajax+node.js best practices for getting started with front-end interaction (in)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.