Native Ajax Introductory Tutorials (with examples)

Source: Internet
Author: User
Tags ibase

Compared to jquery, Yui and some other class library Ajax package, the original JS Ajax seems so embarrassing, compatibility is not good, to remember a lot of method attributes, call inconvenient, code bloated ... But I still want to say that the original JS is the most basic knowledge of the bottom (although the actual project I also to jquery Ajax-based, why? Efficient! ), for the elders of the wood, will be fixed its root.What is Ajax? What is its advantage and disadvantage? Asynchronous JavaScript and XML (asynchronous JavaScript and XML) is a Web development technique for creating interactive Web applications. Simply put it is a combination of a variety of technologies, the purpose is to make the foreground of data interaction becomes faster, do not refresh the page can be done to update the data. The concept of it ends here. Ajax advantages are obvious, conducive to user experience, will not interrupt the user's operation, in the case of not refreshing the page to update the content, reduce the server pressure is also a very hard one of the advantages, but the shortcomings, in addition to the much sought after SEO problems, security issues, forward and backward (although this can be solved with other methods, However, the mechanism of Ajax itself remains the same, and the abnormal mechanism of destroying programs and the imperfect support for the emerging handheld devices are some of the shortcomings that exist. Nobody is perfect, and so is Ajax, and we can't abandon it because it has flaws.where does Ajax need to be?In fact, this is a too broad question, each project has a different use, according to my experience and understanding, Ajax should be used for small area update data and do not want the entire page refresh situation. For example, the user name or registered mailbox, such as data judgment, Content tab content, pop-up registration window, as well as user feedback after the submission of information and so on.Practice the truth! Advocating thinking and practice, I firmly believe that this is a key to any technology into the necessary weapon. Below, I will be a common user to verify whether to use the instance, a little bit to explain the basic Ajax.Verify user name This kind of data judgment, needless to say, will be a little bit front-end people know is necessary. The most traditional mode may be the input information, and then the user point after the alert out a window, tell the user XXX user name has been registered, please re-enter! I hate the extremely ugly alert box! I think most of the users are the same. At this point, Ajax can be a magnificent debut. After the user has entered the name, click anywhere outside the form (lose focus), Ajax quickly feedback the user input to the server-side judgment, and quickly return to a message that the user entered the nickname is available. So, we need a front-desk input form with the following code:

123 < form  name=" Iform "method=" Post "action=" # ", < p >< label  for= "nickname" > User name: </ label >< input  placeholder= "Enter user name here" id= "nickname" Name= "Nickname" type= "text" >< span  id= " Tips "></ span ></ p > </ form >

In addition, we also need a back-end page to determine the existence of the input nickname (in this case, PHP for example, this part does not scrutiny):

12345678910111213141516 ...if(isset($_GET[‘entryname‘])){    $entryname=$_GET[‘entryname‘];}else{    $entryname=‘DATA NULL‘;}$sql=sprintf("select * from i_test_ajax where nickname=‘%s‘",$entryname);$res=$iajax->query($sql);//sleep只是为了展示readState==1时的效果sleep(1);if(($res->num_rows)>0){    echo"抱歉!此昵称已存在 :(";}else{    echo"恭喜!此昵称可注册 :)";}...

So, everything is ready, only owed to the east Wind, the rest of it to the Ajax to deal with. XMLHttpRequest, have to mention an object, Ajax core is also the lowest object. Sadly, it is a standard for the Internet, but Microsoft IE has been very self-(Microsoft IE). What to do? Of course, it's a way to harmonize them. Microsoft IE supports ActiveXObject (' microsoft.xmlhttp ') objects, which is simple:

12345678910 //兼容的XMLHttpRequest对象IXHR: function(){    if(window.ActiveXObject){            XHR=newActiveXObject(‘Microsoft.XMLHTTP‘);        }elseif(window.XMLHttpRequest){            XHR=newXMLHttpRequest();        }else{            returnnull;        }}

A compatible XMLHttpRequest object is implemented, and then a simple onblur event is written, that is, when the value is entered, the form loses focus and starts to judge and quickly feeds back a message to the foreground. The code is as follows:

123456789101112131415161718 //触发焦点时执行document.forms[‘iform‘].nickname.onblur = function(){    //输入的值    varval=document.forms[‘iform‘].nickname.value;    //对用户名的判断    if(!/^[a-zA-Z0-9_]{3,16}$/.test(val)){        alert(‘请输入3~16位由英文、数字、下划线组成的昵称!‘);        returnfalse;    }    //初始化一下XHR    iBase.IXHR();    //原来需要新打开的判断页面用GET使用异步    XHR.open(‘GET‘,‘/demo/ajax/iajax20110306_query.php?entryname=‘+val,true);    //与readyState属性有关,当readyState改变时它才会触发    XHR.onreadystatechange=returnFun;    //异步处理完成后发送数据出去(比如某些需要在焦点事件后再执行的)    XHR.send(null);}

Explain the code in the Ajax section. IBASE.IXHR (), initializes the XHR to ensure compatibility with XMLHttpRequest objects. Next, the validation is sent asynchronously to the/demo/ajax/iajax20110306_query.php page by means of a get. Some people will ask what is Get,get is to request data from the server, get method is to add data parameter queue to a URL, the value and the form is one by one corresponding, such as the entryname=val of this article. This concept may fall within the scope of the background program, not to elaborate. Then, we need to use a onReadyStateChange event property, which is used to store the function (or functions name), whenever the ReadyState property changes, the function is called, that is, the returnfun in this article; Finally, we also send a data to the server , the Send property is typically used for data exchange, and this article is just a simple validation decision, so send a null value. The basic judgment and data transmission is complete, and then there is a key information acquisition, namely Returnfun. Look at the code first:

123456789101112131415 functionreturnFun(){    //当send()已调用,正在发送请求时,显示Loading...    if(XHR.readyState==1){        iBase.Id(‘tips‘).innerHTML=‘Loding...‘;    }elseif(XHR.readyState==4){        //当响应内容解析完成,可以调用时        //更缜密,再判断一下status是否成功        if(XHR.status==200){            //responseText为返回的文本            iBase.Id(‘tips‘).innerHTML=XHR.responseText;        }        //使用完请销毁,避免内存泄露        XHR=null;    }}

This function is used to determine the readystate and status status of the timely feedback to the user corresponding prompt information.   ReadyState has five states: 0 (Uninitialized): The (XMLHttpRequest) object has been created, but the open () method has not been called, 1 (Loaded): The Open () method has been called, but the request has not been sent; 2 (loading completed): The request has been sent to completion; 3 (Interactive): Partial response data can be received, 4 (complete): All data has been received, and the connection is closed. In this way, you should be able to understand the function of the readystate, and the status is actually a secondary state judgment, but the status is more the server side of the state judgment. Regarding status, because it has dozens of kinds of state, I only list a few commonly used: 100--customers must continue to make requests 101--the client requests that the server convert the HTTP protocol version according to the request 200--successful 201--prompt to know the URL of the new file 300--the requested resource can be Get 301--Delete request data in multiple places 404--no file, query, or URL 500--the server generates an internal error now, a simple example of Ajax validation is done: The basic introduction and examples of Ajax is so much, the key is to their own practice and thinking. In fact, this involves knowledge is not complex, if there is the basis of back-end procedures, learning Ajax will be easier, the key is to understand the logic of the relationship. If you are interested, you can write your own Ajax that does not refresh the page to load new content, or consider the Ajax encapsulation of jquery.

Native Ajax Introductory Tutorials (with examples)

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.