This time I will bring you how to use AJAX cache. What are the precautions when using AJAX cache? Here are practical cases, let’s take a look.
I was working on a project using Ajax. I thought it was good at first, but then I found a problem. For example, if I delete an item, I can no longer delete it after restoring it.
I have to wait for a while, but I later found out It's a problem with IE caching
AJAX cache page is a problem that people who are new to AJAX will definitely encounter. The key person causing this problem is Ie...
After looking for a lot of information on the Internet, I summarized Let’s take a look
1: Add a random function after the page requested by AJAX. We can use the random time function
Add t=Math.random() after the URL sent by javascript
Of course, don’t directly add t =Math.random() is copied to the end of the URL, it should look like this: URL "&" "t=" Math.random();
2: Add XMLHttpRequest.setRequestHeader("If-Modified- Since","0")
Under normal circumstances, the XMLHttpRequest here will not be used directly
You should be able to find such code
XXXXX.send(YYYYYY);
Then, change it to
XXXXX.setRequestHeader("If-Modified-Since","0");
XXXXX.send(YYYYYY);
The second method feels good
ajax clear cache Two methods
The first one:
Add
<meta> <meta> <meta>
to the template. The second one:
Add a random number variable to the url
[AJAX introduction]
Ajax is a Web application development method that uses client-side scripts to exchange data with the Web server. Web pages can be updated dynamically without interrupting the interaction process to be re-tailored. Using Ajax, users can create direct, highly available, richer, and more dynamic Web user interfaces that are close to native desktop applications.
Asynchronous JavaScript and XML (AJAX) is not a new technology, but is developed using several existing technologies - including Cascading Style Sheets (CSS), JavaScript, XHTML, XML and Extensible Style Language Transformation (XSLT) Web application software that looks and operates like desktop software.
[AJAX execution principle]
An Ajax interaction starts with a JavaScript object called XMLHttpRequest. As the name implies, it allows a client-side script to perform HTTP requests and will parse an XML-formatted server response. The first step in Ajax processing is to create an XMLHttpRequest instance. Use the HTTP method (GET or POST) to handle the request and set the target URL to the XMLHttpRequest object.
When you send an HTTP request, you don't want the browser to hang and wait for a response from the server. Instead, you want to continue responding to the user's interface interactions through the page and process the server responses once they actually arrive. To accomplish this, you can register a callback function with XMLHttpRequest and dispatch the XMLHttpRequest request asynchronously. Control is immediately returned to the browser, and when the server response arrives, the callback function will be called.
[Practical Application of AJAX]
1. Initialize Ajax
Ajax actually calls the XMLHttpRequest object, so first we must call this object. We build a function to initialize Ajax:
/** * 初始化一个xmlhttp对象 */ function InitAjax() { var ajax=false; try { ajax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { ajax = false; } } if (!ajax && typeof XMLHttpRequest!='undefined') { ajax = new XMLHttpRequest(); } return ajax; }
2. Ajax uses the Get method
Now our first step is to execute a Get request and add the data we need to obtain/show.php?id=1, so what should we do?
Suppose there is a link: News 1. When I click on the link, I can see the content of the link without any refresh. So what do we do?
//Change the link to:
//Set a layer to receive news, and set it not to display:
At the same time, construct the corresponding JavaScript function:
function getNews(newsID) { //如果没有把参数newsID传进来 if (typeof(newsID) == 'undefined') { return false; } //需要进行Ajax的URL地址 var url = "/show.php?id="+ newsID; //获取新闻显示层的位置 var show = document.getElementById("show_news"); //实例化Ajax对象 var ajax = InitAjax(); //使用Get方式进行请求 ajax.open("GET", url, true); //获取执行状态 ajax.onreadystatechange = function() { //如果执行是状态正常,那么就把返回的内容赋值给上面指定的层 if (ajax.readyState == 4 && ajax.status == 200) { show.innerHTML = ajax.responseText; } } //发送空 ajax.send(null); }
This method is suitable for Regarding any element on the page, including forms, etc., in fact, in applications, there are many operations on forms. For forms, the POST method is more commonly used, which will be described below.
3. Ajax uses POST method
In fact, the POST method is similar to the Get method, but it is slightly different when executing Ajax. Let’s briefly describe it.
Assuming there is a form for users to enter information, we save the user information to the database without refreshing and give the user a success prompt.
//构建一个表单,表单中不需要action、method之类的属性,全部由ajax来搞定了。//构建一个接受返回信息的层:
We see that there is no need to submit target and other information in the form above, and the type of submit button is only button, so all operations are performed by the saveUserInfo() function in the onClick event. Let’s describe this function:
function saveUserInfo() { //获取接受返回信息层 var msg = document.getElementById("msg"); //获取表单对象和用户信息值 var f = document.user_info; var userName = f.user_name.value; var userAge = f.user_age.value; var userSex = f.user_sex.value; //接收表单的URL地址 var url = "/save_info.php"; //需要POST的值,把每个变量都通过&来联接 var postStr = "user_name="+ userName +"&user_age="+ userAge +"&user_sex="+ userSex; //实例化Ajax var ajax = InitAjax(); //通过Post方式打开连接 ajax.open("POST", url, true); //定义传输的文件HTTP头信息 ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //发送POST数据 ajax.send(postStr); //获取执行状态 ajax.onreadystatechange = function() { //如果执行状态成功,那么就把返回信息写到指定的层里 if (ajax.readyState == 4 && ajax.status == 200) { msg.innerHTML = ajax.responseText; } } }
4. 异步回调(伪Ajax方式)
一般情况下,使用Get、Post方式的Ajax我们都能够解决目前问题,只是应用复杂程度,当然,在开发中我们也许会碰到无法使用Ajax的时候,但是我们又需要模拟Ajax的效果,那么就可以使用伪Ajax的方式来实现我们的需求。
伪Ajax大致原理就是说我们还是普通的表单提交,或者别的什么的,但是我们却是把提交的值目标是一个浮动框架,这样页面就不刷新了,但是呢,我们又需要看到我们的执行结果,当然可以使用JavaScript来模拟提示信息,但是,这不是真实的,所以我们就需要我们的执行结果来异步回调,告诉我们执行结果是怎么样的。
假设我们的需求是需要上传一张图片,并且,需要知道图片上传后的状态,比如,是否上传成功、文件格式是否正确、文件大小是否正确等等。那么我们就需要我们的目标窗口把执行结果返回来给我们的窗口,这样就能够顺利的模拟一次Ajax调用的过程。
以下代码稍微多一点, 并且涉及Smarty模板技术,如果不太了解,请阅读相关技术资料。
上传文件:upload.html
//上传表单,指定target属性为浮动框架iframe1//显示提示信息的层 //用来做目标窗口的浮动框架 0) { if (move_uploaded_file($_FILES['image']['tmp_name'], USER_IMAGE_PATH . $_FILES['image']['name'])) { $upload_msg ="上传图片成功!"; } else { $upload_msg = "上传图片文件失败"; } } else { $upload_msg = "上传图片失败,可能是文件超过". USER_FACE_SIZE_KB ."KB、或者图片文件为空、或文件格式不正确"; } //解析模板文件 $smarty->assign("upload_msg", $upload_msg); $smarty->display("upload.tpl"); ?> {if $upload_msg != ""} callbackMessage("{$upload_msg}"); {/if} //回调的JavaScript函数,用来在父窗口显示信息 function callbackMessage(msg) { //把父窗口显示消息的层打开 parent.document.getElementById("message").style.display = "block"; //把本窗口获取的消息写上去 parent.document.getElementById("message").innerHTML = msg; //并且设置为3秒后自动关闭父窗口的消息显示 setTimeout("parent.document.getElementById('message').style.display = 'none'", 3000); }
[结束语]
这是一种非常良好的Web开发技术,虽然出现时间比较长,但是到现在才慢慢火起来,也希望带给Web开发界一次变革,让我们朝RIA(富客户端)的开发迈进,当然,任何东西有利也有弊端,如果过多的使用JavaScript,那么客户端将非常臃肿,不利于用户的浏览体验,如何在做到快速的亲前提下,还能够做到好的用户体验,这就需要Web开发者共同努力了。
使用异步回调的方式过程有点复杂,但是基本实现了Ajax、以及信息提示的功能,如果接受模板的信息提示比较多,那么还可以通过设置层的方式来处理,这个随机应变吧。模板文件:upload.tpl 处理上传的PHP文件:upload.php 大致使用POST方式的过程就是这样,当然,实际开发情况可能会更复杂,这就需要开发者去慢慢琢磨。 那么当,当用户点击“新闻1”这个链接的时候,在下面对应的层将显示获取的内容,而且页面没有任何刷新。当然,我们上面省略了show.php这个文件,我们只是假设show.php文件存在,并且能够正常工作的从数据库中把id为1的新闻提取出来。
<a>新闻1</a> <p></p>
你也许会说,这个代码因为要调用XMLHTTP组件,是不是只有IE浏览器能使,不是的经我试验,Firefox也是能使用的。
那么我们在执行任何Ajax操作之前,都必须先调用我们的InitAjax()函数来实例化一个Ajax对象。
url = "xxx.asp?" + Math.round(Math.random()*100) 强制刷新
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to use AJAX cache. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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