ajax technology and application acquaintance

A, ajax technology acquaintance

That AJAX "Asynchronous Javascript And XML" (Asynchronous JavaScript and XML), refers to a web development technology to create interactive web applications. Ajax is not a new programming language, but the use of new methods of existing standards. AJAX can without reloading the entire page, to exchange data with the server. This asynchronous interactive mode, the user clicks, without having to refresh the page can also get new data. With Ajax, users can create near-native desktop applications direct, high availability, richer, more dynamic Web user interface.

Ajax technologies include:

  • XHTML and CSS
  • Using the Document Object Model (Document Object Model) for dynamic display and interaction
  • Using XML and XSLT for data exchange and operation
  • Receiving asynchronous data using XMLHttpRequest

AJAX technology scenarios:

  • When registering, enter your user name automatically detects whether the user already exists.
  • When the login prompt the user name and password error
  • Delete data rows, row ID will be sent to the background, the background to delete the database, the database is deleted successfully, also remove the page rows of data in the DOM.

 

Second, the pseudo application examples ajax

iframe is our common iframe tags: <iframe>. iframe tag is a form of framework, but also to more common, generally used to contain other iframe page, for example, we can load someone else's content website or other pages in the site page on our own website. Iframe tag biggest role is to make the page become beautiful. Iframe tags have many uses, the main difference is in the form of defined different iframe tags, such as the definition of the length and breadth iframe.

Thus, iframe tags having properties locally loaded content, which can be used to forge Ajax request.

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 
 4 import tornado.ioloop
 5 import tornado.web
 6 
 7 
 8 class MainHandler(tornado.web.RequestHandler):
 9     def get(self):
10         # self.write("Hello, world")
11         self.render('index.html')
12 
13     def post(self, *args, **kwargs):
14         self.render('index.html')
15 
16  
. 17  
18 is Settings = {
 . 19      ' template_path ' : ' views ' ,   # view template path 
20 is      ' static_path ' : ' static ' ,    # static file path 
21  }
 22  # route map, routing system 
23 is  DEF make_app ():
 24      return Tornado .web.Application ([
 25          (R & lt " / index " , MainHandler),
 26 is      ], ** Settings)
 27 
28 if __name__ == "__main__":
29     app = make_app()
30     app.listen(8888)
31     tornado.ioloop.IOLoop.current().start()
app.py
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>伪ajax应用</title>
 6 </head>
 7 <body>
 8     <div>
 9         <p>请输入要加载的地址:<span id="currentTime"></span></p>
10         <p>
11             <input id='url' type="text"/>
12             <input type="button" value="提交" onclick="LoadPage();">
13         </p>
14     </div>
15 
16     <div>
17         <h1>加载页面位置:</h1>
18         <iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe>
19     </div>
20 
21     <script type="text/javascript">
22         window.onload = function () {
23             var myDate = new Date();
24             document.getElementById('currentTime').innerText=myDate.getTime();
25         };
26         function LoadPage() {
27             var targeturl = document.getElementById('url').value;
28             document.getElementById('iframePosition').src = targeturl;
29         }
30     </script>
31 </body>
32 </html>
index.html

The results shown:

 

Third, the native acquaintance ajax technology

 The core of Ajax is the XMLHttpRequest object (XHR). XHR resolving server to send a request and in response provides an interface to the server. Able to obtain new data from the server asynchronously.

3.1, XMLHttpRequest Object

The core of Ajax is the XMLHttpRequest object (XHR). XHR resolving server to send a request and in response provides an interface to the server. Able to obtain new data from the server asynchronously.

XHR main methods are:

1. void open(String method,String url,Boolen async)   
   用于创建请求    
   参数:
       method: 请求方式(字符串类型),如:POST、GET、DELETE...
       url:    要请求的地址(字符串类型)
       async:  是否异步(布尔类型)
2. void send(String body) 用于发送请求 参数: body: 要发送的数据(字符串类型)
3. void setRequestHeader(String header,String value) 用于设置请求头 参数: header: 请求头的key(字符串类型) vlaue: 请求头的value(字符串类型) 4. String getAllResponseHeaders() 获取所有响应头 返回值: 响应头数据(字符串类型) 5. String getResponseHeader(String header) 获取响应头中指定header的值 参数: header: 响应头的key(字符串类型) 返回值: 响应头中指定的header对应的值 6. void abort() 终止请求

3.2、XHR的主要属性有:

1. Number readyState
   状态值(整数),可以确定请求/响应过程的当前活动阶段
  • 0:未初始化。未调用open()方法
  • 1:启动。已经调用open()方法,未调用send()方法
  • 2:发送。已经调用send()方法,未接收到响应
  • 3:接收。已经接收到部分数据
  • 4:完成。已经接收到全部数据,可以在客户端使用

2. Function onreadystatechange 当readyState的值改变时自动触发执行其对应的函数(回调函数)
3. String responseText                        作为响应主体被返回的文本(字符串类型)

4. XmlDocument responseXML 服务器返回的数据(Xml对象)

5. Number states 状态码(整数),如:200、404...

6. String statesText 状态文本(字符串),如:OK、NotFound...

 

实例一:GET用于向服务器查询某些信息

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8 
 9     <h1>XMLHttpRequest - Ajax请求</h1>
10     <input type="button" onclick="XmlGetRequest();" value="Get发送请求" />
11 
12     <script src="/statics/jquery-1.12.4.js"></script>
13     <script type="text/javascript">
14 
15         function GetXHR(){
16             var xhr = null;
17             if(XMLHttpRequest){
18                 xhr = new XMLHttpRequest();
19             }else{
20                 xhr = new ActiveXObject("Microsoft.XMLHTTP");
21             }
22             return xhr;
23         }
24         function XmlGetRequest(){
25             var xhr = GetXHR();
26             // 定义回调函数
27             xhr.onreadystatechange = function(){
28                 if(xhr.readyState == 4){
29                     // 已经接收到全部响应数据,执行以下操作
30                     var data = xhr.responseText;
31                     console.log(data);
32                 }
33             };
34             // 指定连接方式和地址----文件方式
35             xhr.open('get', "/test/", true);
36             // 发送请求
37             xhr.send();
38         }
39     </script>
40 </body>
41 </html>
getAjax.html

实例二:POST请求用于向服务器发送应该被保存的数据。POST请求的主体可以包含非常多的数据,而且格式不限。

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title>POST</title>
 6 </head>
 7 <body>
 8 
 9     <h1>XMLHttpRequest - Ajax请求</h1>
10     <input type="button" onclick="XmlPostRequest();" value="Post发送请求" />
11 
12     <script src="/statics/jquery-1.12.4.js"></script>
13     <script type="text/javascript">
14 
15         function GetXHR(){
16             var xhr = null;
17             if(XMLHttpRequest){
18                 xhr = new XMLHttpRequest();
19             }else{
20                 xhr = new ActiveXObject("Microsoft.XMLHTTP");
21             }
22             return xhr;
23         }
24         function XmlPostRequest(){
25             var xhr = GetXHR();
26             // 定义回调函数
27             xhr.onreadystatechange = function(){
28                 if(xhr.readyState == 4){
29                     // 已经接收到全部响应数据,执行以下操作
30                     var data = xhr.responseText;
31                     console.log(data);
32                 }
33             };
34             // 指定连接方式和地址----文件方式
35             xhr.open('POST', "/test/", true);
36             // 设置请求头
37             xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
38             // 发送请求
39             xhr.send('n1=1;n2=2;');
40         }
41     </script>
42 </body>
43 </html>
postAjax.html

 

四、

jQuery 提供多个与 AJAX 有关的方法。

通过 jQuery AJAX 方法,您能够使用 HTTP Get 和 HTTP Post 从远程服务器上请求文本、HTML、XML 或 JSON - 同时您能够把这些外部数据直接载入网页的被选元素中。

  • jQuery 不是生产者,而是大自然搬运工。
  • jQuery Ajax本质 XMLHttpRequest 或 ActiveXObject 

注:2.+版本不再支持IE9以下的浏览器

常用的方法

1. jQuery.get(...)
       所有参数:
              url: 待载入页面的URL地址
             data: 待发送 Key/value 参数。
          success: 载入成功时回调函数。
         dataType: 返回内容格式,xml, json,  script, text, html

2.jQuery.post(...)
       所有参数:
              url: 待载入页面的URL地址
             data: 待发送 Key/value 参数
          success: 载入成功时回调函数
         dataType: 返回内容格式,xml, json,  script, text, html

3.jQuery.getJSON(...)
       所有参数:
              url: 待载入页面的URL地址
             data: 待发送 Key/value 参数。
          success: 载入成功时回调函数。

4.jQuery.getScript(...)
       所有参数:
              url: 待载入页面的URL地址
             data: 待发送 Key/value 参数。
          success: 载入成功时回调函数。

5.jQuery.ajax(...)
       部分参数:
              url:请求地址
             type:请求方式,GET、POST(1.9.0之后用method)
          headers:请求头
             data:要发送的数据
      contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
            async:是否异步
          timeout:设置请求超时时间(毫秒)
       beforeSend:发送请求前执行的函数(全局)
         complete:完成之后执行的回调函数(全局)
          success:成功之后执行的回调函数(全局)
            error:失败之后执行的回调函数(全局)
          accepts:通过请求头发送给服务器,告诉服务器当前客户端课接受的数据类型
         dataType:将服务器端返回的数据转换成指定类型
            "xml": 将服务器端返回的内容转换成xml格式
           "text": 将服务器端返回的内容转换成普通文本格式
           "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
         "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
           "json": 将服务器端返回的内容转换成相应的JavaScript对象
          "jsonp": JSONP 格式使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数

简单实例:
 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <p>
 9         <input type="button" onclick="XmlSendRequest();" value='Ajax请求' />
10     </p>
11     <script type="text/javascript" src="jquery-1.12.4.js"></script>
12     <script>
13         function JXmlSendRequest(){
14             $.ajax({
15                 url: "http://c2.com:8000/test/",    // 访问url地址
16                 type: 'GET',                        // get方式提交
17                 dataType: 'text',            // 数据类型
18                 success: function(data, statusText, xmlHttpRequest){  // 成功后返回的结果
19                     console.log(data);
20                 }
21             })
22         }
23     </script>
24 </body>
25 </html>
jqueryAjax.html

 




Guess you like

Origin www.cnblogs.com/june-L/p/12075574.html