php与Ajax实例
****************AJAX的学习要有JavaScript、HTML、CSS等基本的Web开发能力**************** [AJAX介绍] Ajax是使用客户端脚本与Web服务器交换数据的Web应用开发方法。Web页面不用打断交互流程进行重新加裁,就可以动态地更新。使用Ajax,用户可以创建接近本
****************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的函数:
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;
}
你也许会说,这个代码因为要调用XMLHTTP组件,是不是只有IE浏览器能使,不是的经我试验,Firefox也是能使用的。
那么我们在执行任何Ajax操作之前,都必须先调用我们的InitAjax()函数来实例化一个Ajax对象。
2. 使用Get方式
现在我们第一步来执行一个Get请求,加入我们需要获取 /show.php?id=1的数据,那么我们应该怎么做呢?
假设有一个链接:新闻1,我点该链接的时候,不想任何刷新就能够看到链接的内容,那么我们该怎么做呢?
//将链接改为:
<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.getElementByIdx_x("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);
}
那么当,当用户点击“新闻1”这个链接的时候,在下面对应的层将显示获取的内容,而且页面没有任何刷新。当然,我们上面省略了show.php这个文件,我们只是假设show.php文件存在,并且能够正常工作的从数据库中把id为1的新闻提取出来。
这种方式适应于页面中任何元素,包括表单等等,其实在应用中,对表单的操作是比较多的,针对表单,更多使用的是POST方式,这个下面将讲述。
3. 使用POST方式
其实POST方式跟Get方式是比较类似的,只是在执行Ajax的时候稍有不同,我们简单讲述一下。
假设有一个用户输入资料的表单,我们在无刷新的情况下把用户资料保存到数据库中,同时给用户一个成功的提示。
//构建一个表单,表单中不需要action、method之类的属性,全部由ajax来搞定了。
//构建一个接受返回信息的层:
我们看到上面的form表单里没有需要提交目标等信息,并且提交按钮的类型也只是button,那么所有操作都是靠onClick事件中的 saveUserInfo()函数来执行了。我们描述一下这个函数:
function saveUserInfo()
{
//获取接受返回信息层
var msg = document.getElementByIdx_x("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;
}
}
}
大致使用POST方式的过程就是这样,当然,实际开发情况可能会更复杂,这就需要开发者去慢慢琢磨。
4. 异步回调(伪Ajax方式)
一般情况下,使用Get、Post方式的Ajax我们都能够解决目前问题,只是应用复杂程度,当然,在开发中我们也许会碰到无法使用Ajax的时候,但是我们又需要模拟Ajax的效果,那么就可以使用伪Ajax的方式来实现我们的需求。
伪Ajax大致原理就是说我们还是普通的表单提交,或者别的什么的,但是我们却是把提交的值目标是一个浮动框架,这样页面就不刷新了,但是呢,我们又需要看到我们的执行结果,当然可以使用JavaScript来模拟提示信息,但是,这不是真实的,所以我们就需要我们的执行结果来异步回调,告诉我们执行结果是怎么样的。
假设我们的需求是需要上传一张图片,并且,需要知道图片上传后的状态,比如,是否上传成功、文件格式是否正确、文件大小是否正确等等。那么我们就需要我们的目标窗口把执行结果返回来给我们的窗口,这样就能够顺利的模拟一次Ajax调用的过程。
以下代码稍微多一点, 并且涉及Smarty模板技术,如果不太了解,请阅读相关技术资料。
上传文件:upload.html
//上传表单,指定target属性为浮动框架iframe1
//显示提示信息的层
//用来做目标窗口的浮动框架
处理上传的PHP文件:upload.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']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.getElementByIdx_x("message").style.display = "block";
//把本窗口获取的消息写上去
parent.document.getElementByIdx_x("message").innerHTML = msg;
//并且设置为3秒后自动关闭父窗口的消息显示
setTimeout("parent.document.getElementByIdx_x('message').style.display = 'none'", 3000);
}
使用异步回调的方式过程有点复杂,但是基本实现了Ajax、以及信息提示的功能,如果接受模板的信息提示比较多,那么还可以通过设置层的方式来处理,这个随机应变吧。

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
