Home Backend Development PHP Tutorial PHP开发中AJAX技术的简单应用_PHP

PHP开发中AJAX技术的简单应用_PHP

May 28, 2016 pm 01:13 PM
ajax php application

AJAX无疑是2005年炒的最热的Web开发技术之一,当然,这个功劳离不开Google。我只是一个普通开发者,使用AJAX的地方不是特别多,我就简单的把我使用的心得说一下。(本文假设用户已经具有JavaScript、HTML、CSS等基本的Web开发能力)

[AJAX介绍] Ajax是使用客户端脚本与Web服务器交换数据的Web应用开发方法。Web页面不用打断交互流程进行重新加裁,就可以动态地更新。使用Ajax,用户可以创建接近本地桌面应用的直接、高可用、更丰富、更动态的Web用户界面。   

异步JavaScript和XML(AJAX)不是什么新技术,而是使用几种现有技术——包括级联样式表(CSS)、JavaScript、XHTML、XML和可扩展样式语言转换(XSLT),开发外观及操作类似桌面软件的Web应用软件。

[AJAX执行原理]一个Ajax交互从一个称为XMLHttpRequest的JavaScript对象开始。如同名字所暗示的,它允许一个客户端脚本来执行HTTP请求,并且将会解析一个XML格式的服务器响应。Ajax处理过程中的第一步是创建一个XMLHttpRequest实例。使用HTTP方法(GET或POST)来处理请求,并将目标URL设置到XMLHttpRequest对象上。   

当你发送HTTP请求,你不希望浏览器挂起并等待服务器的响应,取而代之的是,你希望通过页面继续响应用户的界面交互,并在服务器响应真正到达后处理它们。要完成它,你可以向XMLHttpRequest注册一个回调函数,并异步地派发XMLHttpRequest请求。控制权马上就被返回到浏览器,当服务器响应到达时,回调函数将会被调用。

[AJAX实际应用]

1. 初始化Ajax   

Ajax实际上就是调用了XMLHttpRequest对象,那么首先我们的就必须调用这个对象,我们构建一个初始化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;
}
Copy after login

你也许会说,这个代码因为要调用XMLHTTP组件,是不是只有IE浏览器能使,不是的经我试验,Firefox也是能使用的。 那么我们在执行任何Ajax操作之前,都必须先调用我们的InitAjax()函数来实例化一个Ajax对象。

2. 使用Get方式   

现在我们第一步来执行一个Get请求,加入我们需要获取 /show.php?id=1的数据,那么我们应该怎么做呢?   

假设有一个链接:<a href="/show.php?id=1">新闻1</a>,我点该链接的时候,不想任何刷新就能够看到链接的内容,那么我们该怎么做呢?

//将链接改为:
<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); 
}
Copy after login

   那么当,当用户点击“新闻1”这个链接的时候,在下面对应的层将显示获取的内容,而且页面没有任何刷新。当然,我们上面省略了show.php这个文件,我们只是假设show.php文件存在,并且能够正常工作的从数据库中把id为1的新闻提取出来。    这种方式适应于页面中任何元素,包括表单等等,其实在应用中,对表单的操作是比较多的,针对表单,更多使用的是POST方式,这个下面将讲述。

3. 使用POST方式   

其实POST方式跟Get方式是比较类似的,只是在执行Ajax的时候稍有不同,我们简单讲述一下。   

假设有一个用户输入资料的表单,我们在无刷新的情况下把用户资料保存到数据库中,同时给用户一个成功的提示。

//构建一个表单,表单中不需要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>
   我们看到上面的form表单里没有需要提交目标等信息,并且提交按钮的类型也只是button,那么所有操作都是靠onClick事件中的saveUserInfo()函数来执行了。我们描述一下这个函数:
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; 
   } 
  } 
}
Copy after login

   大致使用POST方式的过程就是这样,当然,实际开发情况可能会更复杂,这就需要开发者去慢慢琢磨。

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" style="display:none"></div>
 
//用来做目标窗口的浮动框架
<iframe name="iframe1" width="0" height="0" scrolling="no"></iframe>
处理上传的PHP文件:upload.php
<?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");
 
?>
Copy after login

模板文件: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);
}
Copy after login

   使用异步回调的方式过程有点复杂,但是基本实现了Ajax、以及信息提示的功能,如果接受模板的信息提示比较多,那么还可以通过设置层的方式来处理,这个随机应变吧。

[结束语]这是一种非常良好的Web开发技术,虽然出现时间比较长,但是到现在才慢慢火起来,也希望带给Web开发界一次变革,让我们朝RIA(富客户端)的开发迈进,当然,任何东西有利也有弊端,如果过多的使用JavaScript,那么客户端将非常臃肿,不利于用户的浏览体验,如何在做到快速的亲前提下,还能够做到好的用户体验,这就需要Web开发者共同努力了。

以上就是本文的全部内容,希望对大家掌握AJAX技术在PHP开发中的简单应用有所帮助。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

See all articles