Home > Web Front-end > JS Tutorial > Detailed introduction to jQuery's ajax technology_jquery

Detailed introduction to jQuery's ajax technology_jquery

WBOY
Release: 2016-05-16 17:32:05
Original
1077 people have browsed it
1:Ajax技术包含以下几点:
基于Web标准(XHTML + CSS)的展示
使用DOM进行动态显示和交互
使用XMLHttpRequest进行数据交换和相关操作
使用javascript将所有内容绑定在一起
Ajax的核心是JavaScript的XMLHttpRequest对象,它是一种支持异步请求的技术。简而言之,使用JS可以控制XMLHttpRequest对象向服务器提出请求并处理响应,
而不影响用户对页面的正常访问。对于XMLHttpRequest对象,不同的浏览器提供了不同的支持,IE是将其作为ActiveX控件集成到浏览器中的,而其他主流的浏览器直接
作为一般的JS对象来创建。

2:JS中的Ajax

XMLHttpRequest对象的属性及简要说明

名称

说明

readyState

通信的状态,当XMLHttpRequest对象把一个HTTP请求发送到服务器,到接收到服务器响应信息,整个过程将经历5种状态,该属性取值为为0-4

onreadystatechange

设置回调事件处理程序,当readyState属性的值改变时,会激发此事件

responseText

服务器返回的text/html格式的文档

responseXML

服务器返回的text/xml格式的文档

status

描述了HTTP响应short类型的状态代码,100表示Continue, 101表示Switching protocols数据交换,200表示执行正常,404表示未找到页面,500表示内部程序错误

statusText

HTTP响应的状态代码对应的文本(OK, not found)


readyState属性代码

代码

说明

0

代表未初始化的状态。创建了一个XMLHttpRequest对象,尚未初始化

1

代表连接状态,已经调用了open方法,并且已经准备好发送请求

2

代表发送状态,已经调用了send方法发出请求,尚未得到响应结果

3

代表正在接收状态,已经接收了HTTP响应的头部信息,正在接收响应内容

4

代表已加载状态,此时响应内容已完全被接收


复制代码 代码如下:





Ajax












ajax.js的内容:
复制代码 代码如下:

var xmlRequest;
function CreateRequest()
{
 /* 创建XMLHttpRequest对象 */
 if(window.ActiveXObject)
 {
  return new ActiveXObject("Microsoft.XMLHTTP");
 }
 else if(window.XMLHttpRequest)
 {
  return new XMLHttpRequest();
 }
}
function ResponseHandler()
{
 if(xmlRequest.readyState == 4 && xmlRequest.status == 200)
 {
  /* 如果通信成功,并且响应正常,执行以下操作 */

  var reqContent = xmlRequest.responseText;
  document.getElementById("browser").innerHTML = reqContent;
  document.getElementById("content").value = reqContent;
 }
}
function AjaxAccess()
{
 /* 异步请求百度首页 */

 xmlRequest = CreateRequest();  //创建XMLHttpRequest对象
 xmlRequest.onreadystatechange = ResponseHandler;  //设置回调函数
 xmlRequest.open("GET","http://www.baidu.com");  //初始化请求对象
 xmlRequest.send(null);   //发送请求信息

 /* 触发事件以后提示正在打开百度首页 */
 var brow = document.getElementById("browser");
 brow.innerHTML = "

正在打开百度搜索

";
}
window.onload = function()
{
 document.getElementById("Access").onclick = AjaxAccess;  //设置按扭单击事件
}


3:jQuery中的Ajax
$.ajax(options)方法
options是以“键/值”对的形式设置的,用于设置Ajax请求的参数,如请求方式、请求URL、回调函数等。
常用属性如下:
url:
发送请求的地址
type:请求方式,GET和POST,默认为GET
timeout: 设置请求超时时间,该属性为数值型,单位为毫秒
data: 发送到服务器的数据,“键/值”对形式,该属性可以是对象或者字符串,如果是对象,则自动转换为字符串
dataType:  预期服务器返回的数据类型,该属性为字符串类型。可选值如下: xml、html:返回纯文本HTML信息,包含的标签(script标签或者style标签)会在
文本插入DOM的时候执行、 script:返回纯文本JS代码、json、jsonp、text
contentType: 发送信息至服务器时内容编码类型,该属性为字符串类型,默认值为"application/x-www-form-urlencoded",一般不用设置,因为默认值适合大多数应用场合
beforeSend: 请求发送前的事件,该属性为其设置事件处理程序,可用于发送前修改XMLHttpRequest的参数,如头信息。
复制代码 代码如下:

function(XMLHttpRequest) {
this; /*This keyword here is used to access the options parameter object of the .ajax() method*/
}
complete: Event after the request is completed, whether the request is successful or not, this event will be triggered.
function(XMLHttpRequet, textStatus) {
this; /*This keyword here is used to access the options parameter object of the .ajax() method*/
}
textStatus parameter returns the execution status of the current request (succss and error, etc.)
success: Event when the request is executed successfully.
function(data, textStatus) {
this; /*This keyword here is used to access the options parameter object of the .ajax() method*/
}
error: Events when request execution fails
function(XMLHttpRequest, textStatus, errorThrown) {
this; /*This keyword here is used to access the options parameter object of the .ajax() method*/
}
global: Whether to trigger global Ajax events. This attribute is of Boolean type and the default value is false

Copy code The code is as follows:

$(document).ready(function(){
$("#Access").click(function(){
var xmlReq = $.ajax({
type:'GET',
url:'http://www.sougou.com',
success:function(reqContent)
$ ("#browser").html(reqContent);
$("#content").text(reqContent);
}});
$("#browser").html("< ;h1>Opening Sogou search");
});
});


4: load method
load(url, [data], [callback]);

Copy code The code is as follows:




Load





Reply List





< /html>


Load.js 
Copy code The code is as follows:
$(document).ready(function(){
$("#refresh").click(function(){
/* The URL of the page to be accessed, according to your Make corresponding modifications according to the actual situation*/
var url = "http://www.sogou.com";
$("#commentList").load(url); //Load the corresponding content
} );
});


5: The $.get() method
is a global method, which uses the GET method To make an asynchronous request, the syntax format is as follows:

Copy the code The code is as follows:

         var xmlReq = $.get(url, [data], [callback], [type]);
         $.get("www.baidu.com",
             {
                  user: 'zhangsan'
             }
             );
         callback: function(data, textStatus) {}

复制代码 代码如下:





Get





分类:






Get.js
复制代码 代码如下:

$(document).ready(function(){
 $("#Search").click(function(){

  /* 使用Get方式请求指定URL */
  $.get("http://localhost:2154/Web/BlogList.aspx",
  {
   key : $("#blogClass").val()
  },
  function(data){
   $("#blogList").html(data);
  });
 });

 $("#Search").click();  //触发一次单击事件
});

BlogList.aspx
复制代码 代码如下:

<%@ Page Language="C#" %>
<%
/*
* Add some data to the array respectively,
* These data usually come from Database,
* This is just a simulation, statically added
*/
string[] blogClass = { "CSS", "CSS", ".NET", ".NET", ".NET" , ".NET" };
string[] blogTitle = { "Padding in CSS", "Introduction to CSS", "Classes in C#",
"Basic knowledge of C#", "C# object-oriented", "C# Design Pattern" };

string key = Request["key"]; //Get the keyword of the request server
/*
* Traverse the array collection
*/
for (int i = 0; i < blogClass.Length; i )
{
/*
* If the keyword is empty, display all records
* If the keyword is equal to the category name , display the records under this category
                                                                                                                                                                                                                                                       ;> & Lt; div & gt;
& lt; span & gt; & lt;%= blogclass [i]%& gt; & lt;/span & lt;%= blogtitle [i]%& gt;
/div & div & gt; <; >                                                                      var xmlReq = $.post(url, [data], [callback], [type]);
The $.get() method submits data in GET mode, and all parameter information will be appended to the URL. Web requests generally have certain restrictions on URL length, so the data length passed by the $.get() method also has a certain upper limit.
The $.post() method sends parameters to the server as the entity of the message. For The data length is not affected.




Copy code

The code is as follows:

< title>Post




User login


Username:


Password :
                                                   div>





Post.js





Copy code


The code is as follows:

$(document).ready(function(){
$("#submit").click(function(){
$.post("http://localhost:2154/ Web/Login.aspx",
{
username : $("input[name='username']").val(),
password : $("input[name='password'] ").val()
},
function(data){
$("#login").html(data);
});
});
});

Login.aspx
Copy code The code is as follows:

<%@ Page Language="C#" %>
Welcome <%= Request.Form[" username"] %>


Your identity is Administrator






7: $.getJSON() method
var xmlReq = $.getJSON(url, [data], [callback]);
Copy code The code is as follows:





getJSON










NameAgeSex< /td>




getJSON.js
Copy code The code is as follows:

$(document).ready(function(){
/* Asynchronous request, load JSON data*/ /PeopleList.aspx",
function(data){
/* Traverse the request results*/
$.each(data,
function(index, p){
var html = " " p.name "" p.age
"" (p.isMale ? "male" : " female") ""
$("#peoples>tbody").append(html);
});
});
}) ;


PeopleList.aspx
Copy code The code is as follows:
<%@ Page Language="C#" %>
[{
"name" : "David li",
"age" : 61,
" isMale" : true
},{
"name" : "Michael Clinton",
"age" : 53,
"isMale" : true
},{
"name " : "Brook Ann",
"age" : 23,
"isMale" : false
},{
"name" : "Mary Johnson",
"age" : 35 ,
"isMale" : false
},{
"name" : "Elizabeth Jones",
"age" : 33,
"isMale" : false
},{
"name" : "James Smith",
"age" : 25,
"isMale" : true
}]


8:$.getScript()方法
var xmlReq = $.getScript(url, [callback]);
复制代码 代码如下:





getScript





使用getScript()方法异步加载JavaScript文件






getScript.js 
复制代码 代码如下:

$(document).ready(function(){
 $("#input").click(function(){
  $.getScript("Test.js", function(data){
   showMsg();
  });
 });
});

Test.js 
复制代码 代码如下:

function showMsg(){
 alert("This is Message"); 
}

9:序列化表单数据
jQuery为了解决参数很多的问题,提供了序列化的方法简化对表单数据的收集和格式化。
复制代码 代码如下:





serialize
















Username:
Age:
Sex:
 
Email:
Details:




serialize.js 
复制代码 代码如下:

$(document).ready(function(){
$("button[name='btnSubmit']").click(function(){
$.post("http: //localhost:2154/Web/Register.aspx",
$("form").serialize(), //Serialize form data
function(data){
$("table tbody" ).append("" data "");
});
});
});

Register.aspx
Copy code The code is as follows:

<%@ Page Language="C#" %>
Username:<%= Request["username"] %>


Age :<%= Request["age"] %>


IsMale:<%= Request["isMale"]%>


Email:<%= Request["email"]%>


Details:<%= Request["details"]%>

10: serializeArray() method
This method serializes the page form into a JSON structured object, which is in the form of a collection of "key/value" pairs Encapsulates all element values ​​in the form.
Note here that this method returns a JSON object, not a JSON string
The structure of the JSON object is as follows:
Copy code The code is as follows:

                                                                                                                                                       " , "value": "value2"},
                                                                                                                                               );
var textName = jsonData[0].name;
var textValue = jsonData[0].value;




11: Set global Ajax default options

In applications, a large number of Ajax methods are often written to implement various functions. Each time, a large number of parameters are set in the $.ajax() method, which is very inconvenient. jQuery provides $.ajaxSetup () method, you can set global Ajax default parameter items.
$.ajaxSetup([options]);



Copy code
The code is as follows: $.ajaxSetup({ url: 'Test.html',
type: 'POST',
global: false, //Disable triggering of global events
dataType: 'json',
error: function(xhr, textStatus, errorThrown) {
                                                                                                                     ; 🎜>

ajaxComplete(callback); //This event is triggered when the request is completed
ajaxError(callback); //This event is triggered when an error occurs in the request
ajaxSend(callback); //The request is sent This event is triggered before
ajaxStart(callback); //This event is triggered when the request starts
ajaxStop(callback); //This event is triggered when the request ends
ajaxSuccess(callback); //Triggered when the request is successful The event handler of the
ajaxStart() method and ajaxStop method is a parameterless function, and the rest can have 3 parameters. The syntax format is as follows:

Copy the code

The code is as follows:

Function (Event, XHR, SETTINGS) {
EVENT is a triggered event object
XHR is the XMLHTTPRequest object
Settings are Ajax request configuration parameters





AjaxGlobalEvent










AjaxGlobalEvent.js 
复制代码 代码如下:

$(document).ready(function(){
 $("#show").ajaxStart(function(){
  $(this).append("

Run ajaxStart

");
 });
 $("#show").ajaxStop(function(){
  $(this).append("

Run ajaxStop

");
 });

 $("#show").ajaxComplete(function(){
  $(this).append("

Run ajaxComplete

");
 });

 $("#show").ajaxError(function(){
  $(this).append("

Run ajaxError

");
 });

 $("#show").ajaxSend(function(){
  $(this).append("

Run ajaxSend

");
 });

 $("#show").ajaxSuccess(function(){
  $(this).append("

Run ajaxSuccess

");
 });
 $("button[name='btnLoad']").click(function(){ 
  $.get("http://www.sohu.com");
 }); 
});

   

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template