原生Ajax与jQuery Ajax实现数据交互的对比示例

作者:拾光时间:2026-10-28 17:53:16浏览:235

本文通过一个获取四季信息的Demo,详细对比了原生Ajax与jQuery Ajax在实现后台数据交换时的代码差异。文章提供了完整的HTML、PHP后端及两种Ajax调用方式的JavaScript代码,帮助开发者理解从手动创建XMLHttpRequest对象到使用jQuery封装方法的实现过程,适用于学习前端异步通信技术。

服务器环境搭建与Demo运行说明

前言:本次演示旨在展示如何利用Ajax技术与后台服务器进行数据交互。因此,该Demo必须通过本地服务器环境运行,无法直接通过文件系统打开。搭建服务器环境十分简便,用户可从网络下载WAMP或XAMPP软件并按提示安装。安装完成后,将编写好的页面文件放置于服务器指定的目录中。启动服务后,在浏览器地址栏输入“localhost/指定页面”或“127.0.0.1/指定页面”即可访问。

下文将依次列出该Demo所需的HTML结构代码、PHP后端处理代码、原生Ajax实现代码以及jQuery Ajax实现代码。

HTML页面结构与样式定义

HTML代码部分如下:

代码如下:

<!doctype html>
<html>
<head>
<title>ajax示例</title>
<meta charset='utf-8' />
<link rel="stylesheet" type="text/css" href="css/common.css" />
<style type="text/css">
.main{height:400px;width:800px;margin:100px auto 0;border:1px solid #000;}
.list{height:400px;width:200px;float:left;background:#ddd;}
.inf{height:400px;width:600px;float:right;background:#ccc;text-align:center;}
.list li{width:200px;text-align:center;margin:50px 0 0;font-size:24px;cursor: pointer;
        }
.inf img{width:360px;height:270px;margin:15px auto;}
.inf p{width:580px;text-align:left;text-indent:2em;font-size:14px;margin:0 10px;}
</style>
</head>
<body>
<div class='main'>
<div class='list' id='list'>
<ul>
<li name='spring' id='spring'>春</li>
<li name='summer' id='summer'>夏</li>
<li name='fall' id='fall'>秋</li>
<li name='winter' id='winter'>冬</li>
</ul>
</div>
<div class='inf' id='inf'>
<!--要插入的内容-->
</div>
</div>
</body>
<script type="text/javascript" charset="utf-8" src="js/jQuery.js"></script>
</html>

PHP后端数据处理逻辑

PHP代码部分如下:

代码如下:

<?php
$details = array (
'spring' => "<img src='images/spring.jpg' alt='' /><p>人间四月芳菲尽,山寺桃花始盛开</p>",
'summer' => "<img src='images/summer.jpg' alt='' /><p>水晶帘动微风起,满架蔷薇一院香</p>",
'fall' => "<img src='images/fall.jpg' alt='' /><p>金井梧桐秋叶黄,珠帘不卷夜来霜</p>",
'winter' => "<img src='images/winter.jpg' alt='' /><p>梅须逊雪三分白,雪却输梅一段香</p>"
);
echo $details[$_REQUEST['LiName']];
?>

原生Ajax异步请求实现

原生Ajax实现代码:

代码如下:

<script type="text/javascript">
var lis = document.getElementById('list').getElementsByTagName('li');
window.onload = initPage;
function initPage() {
for (var i=0; i<lis.length; i++) {
txt = lis[i];
txt.onclick = function () {
getDetails(this.id);
            }
        }
    }
function creatRequest() {
try {
request = new XMLHttpRequest();
        }
catch (tryMS) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
            }
catch (otherMS) {
try {
request = new ActiveXObject("Miscrosoft.XMLHTTP");
                }
catch (failed) {
request = null;
                }
            }
        }
return request;
    }
function getDetails(itemName) {
request = creatRequest();
if (request == null) {
alert('没有成功创建请求')
return;
        }
var url = "getDetails.php?LiName="+escape(itemName);
request.open("GET",url,true);
request.onreadystatechange = displayDetails;
request.send(null);
    }
function displayDetails() {
if (request.readyState == 4) {
if (request.status == 200) {
detailDiv = document.getElementById("inf");
detailDiv.innerHTML = request.responseText;
        }
      }
    }   
</script>

jQuery Ajax简化调用方式

jQuery Ajax实现代码:

代码如下:

<script type="text/javascript">
$('#list li').click ( function () {
$.ajax({
type:'GET',
data:'',
url:"getDetails.php?LiName="+this.id,
success:function(data){
$('#inf').html(data);
            },
dataType:'text',
error:function (){
alert("失败!");
            }
        })                    
    });
</script>
作者最新文章