Home >Web Front-end >JS Tutorial >How to use AJAX cache
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 HTTP-EQUIV="pragma" CONTENT="no-cache"> <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate"> <META HTTP-EQUIV="expires" CONTENT="Wed, 26 Feb 1997 08:21:57 GMT">
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来搞定了。 <form name="user_info"> 姓名:<input type="text" name="user_name" /><br /> 年龄:<input type="text" name="user_age" /><br /> 性别:<input type="text" name="user_sex" /><br /> <input type="button" value="提交表单" onClick="saveUserInfo()"> </form> //构建一个接受返回信息的层: <p id="msg"></p>
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 <form action="/upload.php" method="post" enctype="multipart/form-data" name="upload_img" target="iframe1"> 选择要上传的图片:<input type="file" name="image"><br /> <input type="submit" value="上传图片"> </form> //显示提示信息的层 <p id="message" style="display:none"></p> //用来做目标窗口的浮动框架 <iframe name="iframe1" width="0" height="0" scrolling="no"></iframe> <?php /* 定义常量 */ //定义允许上传的MIME格式 define("UPLOAD_IMAGE_MIME", "image/pjpeg,image/jpg,image/jpeg,image/gif,image/x-png,image/png"); //图片允许大小,字节 define("UPLOAD_IMAGE_SIZE", 102400); //图片大小用KB为单位来表示 define("UPLOAD_IMAGE_SIZE_KB", 100); //图片上传的路径 define("UPLOAD_IMAGE_PATH", "./upload/"); //获取允许的图像格式 $mime = explode(",", USER_FACE_MIME); $is_vaild = 0; //遍历所有允许格式 foreach ($mime as $type) { if ($_FILES['image']['type'] == $type) { $is_vaild = 1; } } //如果格式正确,并且没有超过大小就上传上去 if ($is_vaild && $_FILES['image']['size']<=USER_FACE_SIZE && $_FILES['image']['size']>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 href="#" onClick="getNews(1)">新闻1</a> <p id="show_news"></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!