This article mainly introduces the use of ajax and solutions to caching problems in jQuery. Friends in need can come here for reference. I hope it will be helpful to everyone.
1: GET access browser thinks it is idempotent
There is only one result for the same URL [identical means that the entire URL string matches exactly]
So if the URL string does not change during the second visit, the browser will directly take out the result of the first visit
POST is considered a changing access (the browser believes that the submission of POST must have changed)
To prevent the idempotent access of GET, just add it after the URL? new Date();, [In short, it makes the URL string different for each visit]
This principle should also be followed when designing WEB pages
2 : Talking about the difference between Ajax Get and Post
Get method:
The get method can transmit simple data, but the size is average Limited to 1KB, the data is appended to the URL and sent (HTTP header transmission), that is to say, the browser appends each form field element and its data to the end of the resource path in the request line in the format of URL parameters. The most important thing is that it will be cached by the client's browser, so others can read the customer's data, such as account number and password, etc. from the browser's history. Therefore, in some cases, the get method can cause serious security issues.
Post method:
When using the POST method, the browser sends each form field element and its data to the web server as the entity content of the HTTP message. , instead of passing it as a parameter of the URL address, the amount of data transmitted using POST method is much larger than that using GET method.
In short, the GET method transmits a small amount of data, has high processing efficiency and low security, and will be cached, while the opposite is true for POST.
When using the get method, please note:
1 For get requests (or any involving URL transmission parameters), the parameters being passed must first be passed encodeURIComponent method processing. Example:
var url = "update.php?username=" +encodeURIComponent(username) + "&content=" +encodeURIComponent (content)+"&id=1" ;
Please note when using the Post method:
1. Set the Context-Type of the header to application/ x-www-form-urlencode ensures that the server knows that there are parameter variables in the entity. Usually SetRequestHeader("Context-Type", "application/x-www-form-urlencoded;") of the XmlHttpRequest object is used. Example:
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
2. Parameters are key-value pairs with one-to-one name/value correspondence. Each pair of values is separated by an ampersand. For example, var name=abc&sex=man&age=18, note that var name=update .php?abc&sex=man&age=18 and var name=?abc&sex=man&age=18 are both written incorrectly;
3. Parameters are sent in the Send (parameter) method, for example: xmlHttp.send(name ); If it is the get method, directly xmlHttp.send(null);
4. Server-side request parameters distinguish Get and Post. If it is the get method, then $username = $_GET["username"]; If it is the post method, then $username = $_POST["username"];
AJAX garbled problem
Causes of garbled characters:
1. The default character encoding of data returned by xtmlhttp is utf-8, if the client page is gb2312 or other Encoding data will produce garbled characters
2. The default character encoding for data submitted by the post method is utf-8. If the server side is gb2312 or other encoded data, garbled characters will be produced
Solution The methods are:
1. If the client uses gb2312 encoding, specify the output stream encoding on the server
2. Both the server and the client use utf-8 encoding
gb2312:header('Content-Type:text/html;charset=GB2312'); utf8:header('Content-Type:text/html;charset=utf-8');
Note: If you have followed the above method and still return garbled characters, check whether your method is get. For get requests (or any involving url passing parameters), the parameters being passed are all It must be processed by the encodeURIComponent method first. If it is not processed by encodeURIComponent, garbled characters will also be generated.
$.ajax({ type:"GET" url:'test.html', cache:false, dataType:"html", success:function(msg){ alert(msg); } });
jQuery.ajax( options ) : 通过 HTTP 请求加载远程数据
这个是jQuery 的底层 AJAX 实现。简单易用的高层实现见 $.get, $.post 等。
$.ajax() 返回其创建的 XMLHttpRequest 对象。大多数情况下你无需直接操作该对象,但特殊情况下可用于手动终止请求。
注意: 如果你指定了 dataType 选项,请确保服务器返回正确的 MIME 信息,(如 xml 返回 "text/xml")。错误的 MIME 类型可能导致不可预知的错误。见 Specifying the Data Type for AJAX Requests 。
当设置 datatype 类型为 'script' 的时候,所有的远程(不在同一个域中)POST请求都回转换为GET方式。
$.ajax() 只有一个参数:参数 key/value 对象,包含各配置及回调函数信息。详细参数选项见下。
jQuery 1.2 中,您可以跨域加载 JSON 数据,使用时需将数据类型设置为 JSONP。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。数据类型设置为 "jsonp" 时,jQuery 将自动调用回调函数。(这个我不是很懂)
参数列表:
名 类型 描述
url String (默认: 当前页地址) 发送请求的地址。
type String (默认: "GET") 请求方式 ("POST" 或 "GET"), 默认为 "GET"。注意:其它 HTTP 请求方法,如 PUT 和 DELETE 也可以使用,但仅部分浏览器支持。
timeout Number 设置请求超时时间(毫秒)。此设置将覆盖全局设置。
async Boolean (默认: true) 默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
beforeSend Function 发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。XMLHttpRequest 对象是唯一的参数。
function (XMLHttpRequest) { this; // the options for this ajax request }
cache Boolean (默认: true) jQuery 1.2 新功能,设置为 false 将不会从浏览器缓存中加载请求信息。
complete Function 请求完成后回调函数 (请求成功或失败时均调用)。参数: XMLHttpRequest 对象,成功信息字符串。
function (XMLHttpRequest, textStatus) { this; // the options for this ajax request }
contentType String (默认: "application/x-www-form-urlencoded") 发送信息至服务器时内容编码类型。默认值适合大多数应用场合。
data Object,
String 发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2'。
dataType String 预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息返回 responseXML 或 responseText,并作为回调函数参数传递,可用值:
"xml": 返回 XML 文档,可用 jQuery 处理。
"html": 返回纯文本 HTML 信息;包含 script 元素。
"script": 返回纯文本 JavaScript 代码。不会自动缓存结果。
"json": 返回 JSON 数据 。
"jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。
error Function (默认: 自动判断 (xml 或 html)) 请求失败时将调用此方法。这个方法有三个参数:XMLHttpRequest 对象,错误信息,(可能)捕获的错误对象。
function (XMLHttpRequest, textStatus, errorThrown) { // 通常情况下textStatus和errorThown只有其中一个有值 this; // the options for this ajax request }
global Boolean (默认: true) 是否触发全局 AJAX 事件。设置为 false 将不会触发全局 AJAX 事件,如 ajaxStart 或 ajaxStop 。可用于控制不同的Ajax事件:
ifModified Boolean (默认: false) 仅在服务器数据改变时获取新数据。使用 HTTP 包 Last-Modified 头信息判断。
processData Boolean (默认: true) 默认情况下,发送的数据将被转换为对象(技术上讲并非字符串) 以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。
success Function 请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态
function (data, textStatus) { // data could be xmlDoc, jsonObj, html, text, etc... this; // the options for this ajax request }
这里有几个Ajax事件参数:beforeSend ,success ,complete ,error 。我们可以定义这些事件来很好的处理我们的每一次的Ajax请求。注意一下,这些Ajax事件里面的 this 都是指向Ajax请求的选项信息的(请参考说 get() 方法时的this的图片)。
请认真阅读上面的参数列表,如果你要用jQuery来进行Ajax开发,那么这些参数你都必需熟知的。
示例代码,获取博客园首页的文章题目:
$.ajax({ type: "get", url: "http://www.cnblogs.com/rss", beforeSend: function(XMLHttpRequest){ //ShowLoading(); }, success: function(data, textStatus){ $(".ajax.ajaxResult").html(""); $("item",data).each(function(i, domEle){ $(".ajax.ajaxResult").append(" "+$(domEle).children("title").text()+" "); }); }, complete: function(XMLHttpRequest, textStatus){ //HideLoading(); }, error: function(){ //请求出错处理 } });
jQuery.ajaxSetup( options ) : 设置全局 AJAX 默认选项。
设置 AJAX 请求默认地址为 "/xmlhttp/",禁止触发全局 AJAX 事件,用 POST 代替默认 GET 方法。其后的 AJAX 请求不再设置任何选项参数。
jQuery 代码:
$.ajaxSetup({ url: "/xmlhttp/", global: false, type: "POST" }); $.ajax({ data: myData });
serialize() 与 serializeArray() :
serialize() : 序列表表格内容为字符串。
serializeArray() : 序列化表格元素 (类似 '.serialize()' 方法) 返回 JSON 数据结构数据
以上就是本章的全部内容,更多相关教程请访问jQuery视频教程!

实现方法:1、用“$("img").delay(毫秒数).fadeOut()”语句,delay()设置延迟秒数;2、用“setTimeout(function(){ $("img").hide(); },毫秒值);”语句,通过定时器来延迟。

修改方法:1、用css()设置新样式,语法“$(元素).css("min-height","新值")”;2、用attr(),通过设置style属性来添加新样式,语法“$(元素).attr("style","min-height:新值")”。

区别:1、axios是一个异步请求框架,用于封装底层的XMLHttpRequest,而jquery是一个JavaScript库,只是顺便封装了dom操作;2、axios是基于承诺对象的,可以用承诺对象中的方法,而jquery不基于承诺对象。

增加元素的方法:1、用append(),语法“$("body").append(新元素)”,可向body内部的末尾处增加元素;2、用prepend(),语法“$("body").prepend(新元素)”,可向body内部的开始处增加元素。

在jquery中,apply()方法用于改变this指向,使用另一个对象替换当前对象,是应用某一对象的一个方法,语法为“apply(thisobj,[argarray])”;参数argarray表示的是以数组的形式进行传递。

删除方法:1、用empty(),语法“$("div").empty();”,可删除所有子节点和内容;2、用children()和remove(),语法“$("div").children().remove();”,只删除子元素,不删除内容。

去掉方法:1、用“$(selector).removeAttr("readonly")”语句删除readonly属性;2、用“$(selector).attr("readonly",false)”将readonly属性的值设置为false。

on()方法有4个参数:1、第一个参数不可省略,规定要从被选元素添加的一个或多个事件或命名空间;2、第二个参数可省略,规定元素的事件处理程序;3、第三个参数可省略,规定传递到函数的额外数据;4、第四个参数可省略,规定当事件发生时运行的函数。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

SublimeText3 English version
Recommended: Win version, supports code prompts!
