Home > Backend Development > PHP Tutorial > Simple application of AJAX technology in PHP development_PHP tutorial

Simple application of AJAX technology in PHP development_PHP tutorial

WBOY
Release: 2016-07-13 17:38:08
Original
941 people have browsed it

AJAX is undoubtedly one of the hottest web development technologies in 2005. Of course, this credit cannot be separated from 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, CSS, etc.)

[AJAX introduction]

Ajax is a web application development method that uses client-side scripts to exchange data with a 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 suggests, 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.

[AJAX practical application]

1. Initialize Ajax

Ajax actually calls the XMLHttpRequest object, so first we must call this object. We build a function that initializes 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;
}
* Initialize an xmlhttp object*/ 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 get /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 should we do? Woolen cloth?

//Change the link to:
//将链接改为:
<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);
}
<a href="#" onClick="getNews(1)">News 1</a>

//And set a layer to receive news, and set it not to display:
<div id="show_news"></div>

At the same time, construct the corresponding JavaScript function:

function getNews(newsID)
{
//If the parameter newsID is not passed in
if (typeof(newsID) == undefined)
{
//构建一个表单,表单中不需要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>
return false; } //URL address required for Ajax var url = "/show.php?id="+ newsID; //Get the position of the news display layer var show = document.getElementById("show_news"); //Instantiate Ajax object var ajax = InitAjax(); //Use the Get method to make a request ajax.open("GET", url, true); //Get execution status ajax.onreadystatechange = function() { //If the execution status is normal, then assign the returned content to the layer specified above ​if (ajax.readyState == 4 && ajax.status == 200) {   show.innerHTML = ajax.responseText; } } //Send empty 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 more commonly used, which will be described below. 3. Use 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.
//Construct a form. There is no need for attributes such as action and method in the form. It is all done by ajax. <form name="user_info"> Name:<input type="text" name="user_name" /><br /> Age:<input type="text" name="user_age" /><br /> Gender:<input type="text" name="user_sex" /><br /> <input type="button" value="Submit form" onClick="saveUserInfo()"> </form> //Build a layer that accepts return information: <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 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()
{
//Get the acceptance return information layer
var msg = document.getElementById("msg");

//Get the form object and user information value
var f = document.user_info;
var userName = f.user_name.value;
var userAge = f.user_age.value;
var userSex = f.user_sex.value;

//The URL address of the receiving form
var url = "/save_info.php";

//Need POST value, connect each variable through &
var postStr = "user_name="+ userName +"&user_age="+ userAge +"&user_sex="+ userSex;

//Instantiate Ajax
var ajax = InitAjax();

//Open the connection through Post method
ajax.open("POST", url, true);

//Define the transferred file HTTP header information
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

//Send POST data
ajax.send(postStr);

//Get execution status
ajax.onrea

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486518.htmlTechArticleAJAX is undoubtedly one of the hottest web development technologies in 2005. Of course, this credit cannot be separated from Google . I'm just an ordinary developer. I don't use AJAX very much, so I simply...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template