JavaScript learns to summarize Ajax and HTTP status words

Source: Internet
Author: User

Ajax and how it works

AJAX is a technology that exchanges data with the server without having to refresh the Web page, which was first used by Google in Google Maps and quickly swept through.

Ajax is not cross-domain, such as cross-domain, can use document.domain=‘a.com‘; or use the server proxy, proxy XMLHttpRequest file

Ajax is based on existing Internet standards and uses them together:

XMLHttpRequest 对象 (异步的与服务器交换数据)JavaScript/DOM (信息显示/交互)CSS (给数据定义样式)XML (作为转换数据的格式)

Create a XMLHttpRequest Object

All modern browsers (ie7+, Firefox, Chrome, Safari, and Opera) are built XMLHttpRequest -in objects.

To create an Ajax object:

//IE6以上var oAjax = new XMLHttpRequest();//IE6var oAjax =new ActiveXObject("Microsoft.XMLHTTP")
Connecting to a server
oAjax.open(方法,url,是否异步)

As we all know, Ajax Asynchronous Javascript And XML is "" (Asynchronous JavaScript and XML), which is a web development technique for creating interactive Web applications. So, Ajax is inherently working in asynchronous mode (Async is True, synchronization is false)

Synchronous and asynchronous

Synchronization means that after the sender sends out the data, the receiver sends back the response before sending the next packet to the communication mode.
Asynchronous means that after the sender sends out the data, the receiver sends back the response, and then the next packet is communicated.
(The simple point: synchronization is only one thing to do, and async is can be done at the same time more than one thing)

Send request to send ()
<ScriptType="Text/javascript" >functionGetdoc(){var xmlhttp;IfWindow.xmlhttprequest) {xmlhttp=New XMLHttpRequest (); }else{xmlhttp =New ActiveXObject ("Microsoft.XMLHTTP");For IE6} Xmlhttp.onreadystatechange =function(){if (xmlhttp.readystate==4&&xmlhttp.status==200) { document.getelementbyid ( "MyId"). innerhtml= Xmlhttp.responsetext; }} xmlhttp.open ( "? GET ", Index.php,true); Xmlhttp.send ();} </script></ head><body> <button type=  "button" onclick= "GetDoc ()" > Request data </button></ body>             

GET or POST?

GET is simpler and faster than POST, and can be used in most cases.

However, use the POST request in the following cases:

无法使用缓存文件(更新服务器上的文件或数据库)向服务器发送大量数据(POST 没有数据量限制)发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠
Receive return information
function(){   //当请求状态改变时要调用的事件处理器    alert(oAjax.readystate);           }

readyStatean event is triggered whenever the value of the property changes readyStatechange . This event can be used to detect the value of readystate after each state change. In general, we are only interested in stages where the readystate value is 4, because all the data is now ready, but you must open() specify the event handler before the call onreadystatechange to ensure cross-browser compatibility. Let's look at an example:

var xhr = createXHR();xhr.onreadystatechange = function () {    if (xhr.readyState == 4) { if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { alert(xhr.statusText); } else { alert("Request was unsuccessful: " + xhr.status); } }};xhr.open("get", "example.txt", true);xhr.send(null);
XHR Object

XMLHttpRequestProperties of this object:

Its properties are:

onreadystatechange  每次状态改变所触发事件的事件处理程序。responseText     从服务器进程返回数据的字符串形式。responseXML    从服务器进程返回的DOM兼容的文档数据对象。status           从服务器返回的数字代码,比如常见的404(未找到)和200(已就绪)status Text       伴随状态码的字符串信息

When the XHR object sends an HTTP request to the server, it undergoes several states until the request is processed before receiving a response. readyStateis the state property of the XHR request, which itself has 5 property values:

0(未初始化)还没有调用open()方法1(载入)已调用send()方法,正在发送请求2(载入完成)send()方法完成,已收到全部响应内容3(解析)正在解析响应内容4(完成)响应内容解析完成,可以再客户端使用了
HTTP status Code

1-Word Header: message. This type of status code, on behalf of which the request has been accepted, needs to be processed.
2 Word head: success. This type of status code indicates that the request has been successfully received, understood, and accepted by the server.
3-Word Header: redirect. This type of status code represents the need for the client to take further action to complete the request.
4-Word Header: Client error. This type of status code indicates that the client may appear to have errors that prevent the server from processing.
5-Word Header: Server error. This type of status code indicates that the server has an error or an abnormal state occurred during the processing of the request.

Additional: HTTP status code detailed
W3cschool HTTP Status message: http://www.w3school.com.cn/tags/html_ref_httpmessages.asp

Status and StatusText

  statusTextis the text information returned by the response, which can only be readyState used if the value is 3 or 4. The readyState view Access property throws an exception when it is a different value statusText .

Methods of XHR
Method Description
Abort () Causes the currently executing request to be canceled
getAllResponseHeaders () Returns a single character that contains the names and values of all response headers
getResponseHeader (name) Returns the name and value specified in the response header
Open (METHOD,URL,ASYNC,USERNAME,PWD) Set the HTTP method (get or post), etc.
Send (content) Issue a request with the specified principal content
setRequestHeader (Name,value) Sets the request header with the specified name and value

<ScriptType="Text/javascript" > var oajax =oajax (); alert (oajax.readystate);//popup "0" Oajax.open ( "get",  " Index.html ", true); alert (oajax.readystate); //pops up "1" oajax.send (null); alert (oajax.readystate); //ie under the pop-up 4, and Firefox is 2 //can be monitored by readystatechange event oajax = XHR (); Oajax.onreadystatechange = function //ie is 1,1,3,4}; Oajax.open ( "get",  "Index.txt",  true); Oajax.send (null); SCRIPT>           
Ajax in jquery

.load()The method is a local method, because he needs an object containing the element jQuery as a prefix, $.get() and a $.post() global method, without specifying an element, for the purpose of the .load() asynchronous acquisition of static files, and for the need to pass parameters to the server page, $.get() and $.post()more appropriate.

The Get and post incoming data is a key-value pair object, the difference is that the get incoming data is transmitted through the address bar, and the post is submitted through the form,

$(function () {    $("input").click(function () { $.get(‘test.php?url=baidu.com‘, function (response,status,xhr) { $(‘#box‘).html(response); }) })});

POSTThe commit cannot use the url pass parameter. postcommits can be passed as a string of key-value pairs, and automatically converted to HTTP message entity-pass parameters

$(function () {    $("input").click(function () { $.post(‘test.php‘,‘url=baidu.com‘, function (response,status,xhr) { $(‘#box‘).html(response); }) })});
//post提交可以使用对象键值对$(function () {    $("input").click(function () { $.post(‘test.php‘,{ url:‘baidu.com‘//post提交可以使用对象键值对 }, function (response,status,xhr) { $(‘#box‘).html(response); }) })});

$.get()The method has four parameters, the first three parameters and the .load() same, more than one of the four parameters, that is, the type content format returned by the server, including xml,json,script,html,text , and so on, one parameter is required, followed by three optional parameters

$.ajax()is the lowest method in all Ajax methods, all other methods are based on $.ajax() method encapsulation, this method has only one parameter, passing a
The object for each function key-value pair.

$.ajax () method object parameter list object sent to server, key value pair string or object
Parameters type Description
url string send the requested address
type string request method, default get
timeout number Set the time the request timed out
data object or string
datatype string Data types returned, such as Html,xml,json
success function callback function called after successful request
complete function
error function callback function called after request failed
$(function () {    $("input").click(function () { $.ajax({ type : "POST", url: ‘test.php‘, data:{ url: ‘baidu.com‘ }, success : function(response,status,xhr){ $(‘#box‘).html(response); } }) })});
Serialization of Forms

AjaxThe most common place to use is the form operation, while the traditional form action is to submit commit the data transfer to the server by committing, if using Ajax asynchronous processing
, we need to get each form element to be submitted, so productivity is greatly reduced

<Body><Formaction="" > User name:<InputType="Text"Name="User"/> Mail:<InputType="Text"Name="Email"/><InputType="Button"Value="Submit"/></Form><DivId="Box" ></Div><ScriptType="Text/javascript" > $ (function  () {$ ( "form Input[type=button]"). Click (function  () {$.ajax ({type:  ' POST ', URL:  ' test.php ', data: {User: $ ( ' form Input[name=user] '). Val (), Email: $ ( "form Input[name=email]"). Val (),}, Success: function (response) {$ ( "#box"). HTML ( Response); } }) }) }); </script></ BODY>             

In cases where the form element is particularly numerous, form serialization should be used, that is, a data:$(“form”).serialize(); string key-value pair is obtained, and the url encoding

serialize()Method not only can serialize elements within a form, but also directly get the contents of a radio box, a check box, a drop-down list box, and so on

<Body><Formaction="" > User name:<InputType="Text"Name="User"/> Mail:<InputType="Text"Name="Email"/><InputType="Button"Value="Submit"/><InputType="Radio"Name="Sex"Value="Male"/> Male<InputType="Radio"Name="Sex"Value="Female"/> Female<InputType="Button"Value="Submit"/></form><div id= "box" ></ div><script>  $ (function  () {$ ( "form Input[name=sex]"). Click (function  () {$ ( ' #box '). HTML (decodeuricomponent ($ (this). Serialize ()); })}) </script></ BODY>             
Traditional AJAX issues

The traditional ajax problem is as follows:

1、可以无刷新改变页面内容,但无法改变页面URL2、为了更好的可访问性,内容发生改变后,通常改变URL的hash3、hash的方式不能很好的处理浏览器的前进、后退等问题4、进而浏览器引入了onhashchange的接口,不支持的浏览器只能定时去判断hash是否改变5、但这种方式对搜索引擎很不友好6、twitter和google约定了使用#!xxx(即hash第一个字符为!),搜索引擎进行支持。

JavaScript learns to summarize Ajax and HTTP status words

Related Article

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.