Analysis on the principle and usage of Ajax

Source: Internet
Author: User

1 Ajax Principles
    Ajax(Asynchronous JavaScript and XML (异步的JavaScript和XML)),是一种快速创建动态网页的技术,目的是显示动态局部刷新.通过XMLHttpResponse对象来向服务器发起异步请求,从服务器获取数据.(1) 异步的javascript: 使用javaScript语言及功能向服务器发起请求,当服务器处理完请求之后,自动执行javaScript回调函数.(客户端可以不需要等到服务器响应才能运行)(2) XML是一种标记语言,是ajax与后台交互传输数据格式之一(3) ajax只能向同源网站发起Http请求(端口,协议,域名都相同),跨域请求会报错利用Ajax可以实现:1 注册时,输入用户名自动检测该用户是否存在2 登录时提示密码用户名错误3 页面局部进行更新数据
2 Xmlhttpresponse Basic Properties
(1) onreadystatechange  每次状态改变所触发事件的时间处理程序(2) responseText  从服务器响应返回字符串形式数据(3) responseXML   从服务器响应返回以XML(DOM兼容文档)数据对象(4) response      从服务器返回对象:如json对象(5) timeout  表示多少毫秒后,如果请求仍然没有得到结果,就会自动终止附: response类型由XMLHttpRequest.responseType属性的值决定    ‘‘:           字符串    ‘document‘:   Document对象    ‘json‘:       json对象    ‘text‘:       字符串    ‘blob‘:       Blob对象,适合读取二进制文件var ajax = new XMLHttpRequest();ajax.open(‘GET‘, ‘http://www.example.com/page.php‘, true);var data = ajax.responseText;data = JSON.parse(data);   将json字符串转json对象var last=JSON.stringify(obj)   将json对象转字符串
3 Ajax Status Codes
200, OK,访问正常301, Moved Permanently,永久移动302, Move temporarily,暂时移动304, Not Modified,未修改307, Temporary Redirect,暂时重定向401, Unauthorized,未授权403, Forbidden,禁止访问404, Not Found,未发现指定网址500, Internal Server Error,服务器发生错误
4 Setting the Listener interface
onloadstart  请求发出onprogress   正在发送和加载数据onerror      请求失败onload       请求成功完成ontimeout    用户指定的时限到期,请求还未完成onloadend    请求完成,不管成果或失败
5 ajax in native JavaScript
{1} Synchronous Ajax request, GET request: #定义一个触发函数fresh_codefunction Fresh_code () {Let xhr = new XMLHttpRequest () Xhr.open (' Get '  , '/api/v1/regist_code ', false);  False stands for synchronization, true for asynchronous request Xhr.send () Let Regist_code = xhr.responsetext//write the registration code to the Regist_code tag Regist_code_span = document.getElementById (' regist_code ') regist_code_span.innerhtml = Regist_code} {2} async Aja x request, GET request: var xhr = new XMLHttpRequest ();//Specifies the callback function when the state changes during the communication Xhr.onreadystatechange = function () {//When the communication succeeds, the status value is 4,          Status code is (xhr.readystate = = = 4 && Xhr.status = =) {//xhr.response refers to the received ResponseText string          var data=json.parse (Xhr.responsetext);    Console.log (data)} else {console.error (xhr.statustext); }}};xhr.onerror = function (e) {console.error (xhr.statustext);};/ The/Open method is used to specify the HTTP verb, the URL of the request, whether to asynchronously Xhr.open (' GET ', '/endpoint ', true);//Send HTTP request xhr.send (NULL); {3} Synchronous Ajax request, POST request var name = encodeURI ("Beijing West"); var data = "Username=" + name + "&AMp;password=123 ";//Call to send () function send (data), function Send (ARG) {//Call to create Object function Createxmlhttprequest ();  Xmlhttp.onreadystatechange = Callhandle;  Get notation (Request mode, URL, synchronous or asynchronous) directly stitching to the URL, sending//xmlhttp.open ("GET", "default.aspx?goback=yes&arg=" + arg,true); Post notation (request mode, URL, synchronous or asynchronous), requires additional settings for the request header Xmlhttp.open ("Post", "Http://172.16.5.25:9011/dynamicStation/loginByAdmin",  true);    When using post, must have this sentence Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded;"); Xmlhttp.send (ARG);} function Createxmlhttprequest () {#创建xmlhttp对象, make a decision if (window.  ActiveXObject) {xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP"); } else if (window.  XMLHttpRequest) {xmlhttp = new XMLHttpRequest (); }}
4 jquery in Ajax
$.ajax({    #请求方式    type:‘get‘,    url:‘/studentsinfo‘,    #请求格式为json    dataType:‘json‘,    #处理函数    success:function(data,status){        console.log(data)        var d=data[‘data‘]        for(var i=0;i<d.length;i++){            document.write(‘<p>‘+d[i][0]+‘</p>‘)        }      }})也可以直接使用$get  或者  $post 基本类似ajax的调用,只是在请求方式这块不用指定,原理一致!!

Today to share this, like the small partners can point out the recommendation Oh!! Thank you so much!!

Analysis on the principle and usage of Ajax

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.