Detailed introduction to jQuery's ajax technology_jquery
基于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.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
$(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]);
Reply List
< /html>
Load.js
$("#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:
var xmlReq = $.get(url, [data], [callback], [type]);
$.get("www.baidu.com",
{
user: 'zhangsan'
}
);
callback: function(data, textStatus) {}
分类:
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
< 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
<%@ Page Language="C#" %>
Welcome <%= Request.Form[" username"] %>
Your identity is Administrator
7: $.getJSON() method
var xmlReq = $.getJSON(url, [data], [callback]);
Name | Age | Sex< /td> |
html>
getJSON.js
$(document).ready(function(){
/* Asynchronous request, load JSON data*/ /PeopleList.aspx",
function(data){
/* Traverse the request results*/
$.each(data,
function(index, p){
var html = "
"
$("#peoples>tbody").append(html);
});
});
}) ;
PeopleList.aspx
[{
"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()方法异步加载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.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("
});
});
});
Register.aspx
<%@ 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:
" , "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
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
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.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");
});
});


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.
