Home >Backend Development >PHP Tutorial >Simple application of AJAX technology in PHP development, ajax technology php development_PHP tutorial
AJAX is undoubtedly one of the hottest web development technologies in 2005. Of course, this credit goes to Don't open Google. I am just an ordinary developer and I don’t use AJAX very much. I will simply share my experience in using it. (This article assumes that the user already has basic web development capabilities such as JavaScript, HTML, and CSS)
[Introduction to AJAX] 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 uses several existing technologies - including Cascading Style Sheets (CSS), JavaScript, XHTML, XML and Extensible Style Language Transformations (XSLT) to develop look and action Web application software similar to 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; }
You may say that because this code calls the XMLHTTP component, it can only be used by IE browser. No, after my test, Firefox can also be used. Then before we perform any Ajax operations, we must first call our InitAjax() function to instantiate an Ajax object.
2. Use 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: <a href="/show.php?id=1">新闻1</a>
. When I click on the link, I can see the content of the link without any refresh. So what should we do?
//将链接改为: <a href="#" onClick="getNews(1)">新闻1</a> //并且设置一个接收新闻的层,并且设置为不显示: <div id="show_news"></div> 同时构造相应的JavaScript函数: 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); }
Then when the user clicks the "News 1" link, the obtained content will be displayed in the corresponding layer below, and the page will not be refreshed. Of course, we omitted the show.php file above. We just assumed that the show.php file exists and can extract the news with ID 1 from the database normally. This method is suitable for any element on the page, including forms, etc. In fact, in applications, there are many operations on forms. For forms, the POST method is mostly used, which will be described below.
3. Use the 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. Suppose 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> //构建一个接受返回信息的层: <div id="msg"></div>
We see that there is no need to submit target and other information in the form above, and the type of the 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; } } }
The process of using the POST method is roughly like this. Of course, the actual development situation may be more complicated, which requires developers to think about it slowly.
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> //显示提示信息的层 <div id="message"><?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"); ?> 模板文件: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); }
使用异步回调的方式过程有点复杂,但是基本实现了Ajax、以及信息提示的功能,如果接受模板的信息提示比较多,那么还可以通过设置层的方式来处理,这个随机应变吧。
[结束语] 这是一种非常良好的Web开发技术,虽然出现时间比较长,但是到现在才慢慢火起来,也希望带给Web开发界一次变革,让我们朝RIA(富客户端)的开发迈进,当然,任何东西有利也有弊端,如果过多的使用JavaScript,那么客户端将非常臃肿,不利于用户的浏览体验,如何在做到快速的亲前提下,还能够做到好的用户体验,这就需要Web开发者共同努力了。