JSON与AJAX的使用指南
1. 使用XMLHttpRequest
在Web开发中,
XMLHttpRequest
对象是实现异步数据交互的关键工具。下面通过几个示例来详细介绍其使用方法。
1.1 修改页面元素内容
以下是一个使用
XMLHttpRequest
对象替换
<p>
标签内容的示例代码:
<html>
<head></head>
<body>
<p>Original content</p>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
// 分配请求属性
xhr.open("GET", window.location.pathname, true);
// 定义回调函数
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) { // 就绪状态4表示完成
var message = "";
if (xhr.status == 200) { // 成功
message = "Ajax loaded content";
} else { // 错误
message = "An error has occured making the request";
}
document.getElementsByTagName("p")[0].innerHTML = message;
}
}
// 发送实际请求
xhr.send(null);
</script>
</body>
</html>
在上述代码中,
open()
方法的URL使用的是当前页面,通过
window.location.pathname
获取。
xhr.send(null)
表示在Ajax调用中不发送数据。需要注意的是,JavaScript代码放在要操作的HTML元素之后,这是为了确保DOM树完全加载后,JavaScript能够找到并操作其中的元素。而像jQuery这样的高级框架有测试文档是否就绪的函数,允许将JavaScript代码放在页面的任何位置。
1.2 获取外部XML文件的纯文本内容
下面的代码展示了如何使用
XMLHttpRequest
获取外部XML文件的纯文本内容,并将其显示在页面上:
<html>
<head>
<title>XHR Example</title>
<style type="text/css">
#generated_content {
border: 1px solid black;
width: 300px;
background-color: #dddddd;
}
</style>
</head>
<body>
<p><strong>Ajax grabbed plain text:</strong></p>
<div id="generated_content"> </div>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
// 分配请求属性
xhr.open("GET", "animals.xml", true);
// 定义回调函数
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) { // 就绪状态4表示完成
var message = "";
if (xhr.status == 200) { // 成功
// 以纯文本形式检索结果
message = "<pre>" + xhr.responseText + "</pre>";
} else { // 错误
message = "An error has occured making the request";
}
document.getElementById("generated_content").innerHTML = message;
}
}
// 发送实际请求
xhr.send(null);
</script>
</body>
</html>
这里使用的
animals.xml
文件内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<animals>
<dogs>
<dog>
<name>snoopy</name>
<color>brown</color>
<breed>beagle cross</breed>
</dog>
<dog>
<name>jade</name>
<color>black</color>
<breed>lab cross</breed>
</dog>
</dogs>
<cats>
<cat>
<name>teddy</name>
<color>brown</color>
<breed>tabby</breed>
</cat>
</cats>
</animals>
在上述代码中,关键的是在请求成功时,将响应的纯文本内容赋值给变量
message
,并将其设置为
id
为
generated_content
的
<div>
元素的
innerHTML
。
1.3 解析XML文件中的特定值
若要获取XML文件中特定元素的值,可按以下代码实现:
<html>
<head>
<title>XHR Example - XML</title>
<style type="text/css">
#generated_content {
border: 1px solid black;
width: 300px;
background-color: #dddddd;
padding: 20px;
}
</style>
</head>
<body>
<p><strong>Ajax grabbed specific XML below:</strong></p>
<div id="generated_content"> </div>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
// 分配请求属性
xhr.open("GET", "animals.xml", true);
// 定义回调函数
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) { // 就绪状态4表示完成
var message = "";
if (xhr.status == 200) { // 成功
var xml_data = xhr.responseXML;
// 以XML对象形式检索结果
var names = xml_data.getElementsByTagName("name");
for (i = 0; i < names.length; ++i) {
message += names[i].firstChild.nodeValue + "<br/>\n";
}
} else { // 错误
message = "An error has occured making the request";
}
document.getElementById("generated_content").innerHTML = message;
}
}
// 发送实际请求
xhr.send(null);
</script>
</body>
</html>
此代码通过
xhr.responseXML
获取XML数据,并使用
getElementsByTagName
方法解析出所有
<name>
元素的值。
1.4 获取HTML文件内容
当请求的是HTML文件时,使用
responseText
可以保留HTML结构,示例代码如下:
<html>
<head>
<title>XHR Example - Plain Text Containing HTML</title>
<style type="text/css">
#generated_content {
border: 1px solid black;
width: 300px;
background-color: #dddddd;
}
</style>
</head>
<body>
<p><strong>Ajax grabbed plain text containing html:</strong></p>
<div id="generated_content"> </div>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
// 分配请求属性
xhr.open("GET", "sample_table.html", true);
// 定义回调函数
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) { // 就绪状态4表示完成
var message = "";
if (xhr.status == 200) { // 成功
message = xhr.responseText; // 以纯文本形式检索结果
} else { // 错误
message = "An error has occured making the request";
}
document.getElementById("generated_content").innerHTML = message;
}
}
// 发送实际请求
xhr.send(null);
</script>
</body>
</html>
其中
sample_table.html
文件内容为:
<table border="1">
<tr><th>foo</th><th>bar</th></tr>
<tr><th>a</th><th>1</th></tr>
<tr><th>b</th><th>2</th></tr>
<tr><th>c</th><th>3</th></tr>
</table>
2. 高级JavaScript API
像jQuery、Prototype和YUI等高级JavaScript API越来越受欢迎,原因在于它们简化了复杂对象(如
XMLHttpRequest
)的使用,让开发者无需深入了解其内部工作原理。同时,这些库还能更方便地实现跨浏览器支持和DOM操作。
2.1 jQuery示例
以下是使用jQuery实现与上述
XMLHttpRequest
示例相同功能的代码。
2.1.1 修改
<p>
元素内容
<html>
<head>
<title>First jQuery Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "get",
url: window.location.pathname,
dataType: "text",
success: function (data) {
$("p").html("Ajax loaded content");
},
failure: function () {
$("p").html("An error has occurred making the request");
}
});
});
</script>
</head>
<body>
<p>Original content</p>
</body>
</html>
在这个示例中,通过
$.ajax
方法发起请求,它接收请求类型、URL和响应数据类型等参数,并定义了成功和失败的回调函数。
$(document).ready
函数确保在DOM文档完全加载后执行脚本,使得脚本可以放在HTML文档中要操作的元素之前。
2.1.2 加载XML文件的纯文本内容
<html>
<head>
<title>Loading Plain Text with jQuery</title>
<style type="text/css">
#generated_content {
border: 1px solid black;
width: 300px;
background-color: #dddddd;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "get",
url: "animals.xml",
dataType: "text",
success: function (data) {
$("#generated_content").html("<pre>" + data + "</pre>");
},
failure: function () {
$("#generated_content").html("An error has occured making the request");
}
});
});
</script>
</head>
<body>
<p><strong>Ajax grabbed plain text:</strong></p>
<div id="generated_content"> </div>
</body>
</html>
若不考虑错误处理,代码可以简化为:
<html>
<head>
<title>Loading Plain Text with jQuery</title>
<style type="text/css">
#generated_content {
border: 1px solid black;
width: 300px;
background-color: #dddddd;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#generated_content").load("animals.xml");
$("#generated_content").wrap("<pre>");
});
</script>
</head>
<body>
<p><strong>Ajax grabbed plain text:</strong></p>
<div id="generated_content"> </div>
</body>
</html>
这里使用了jQuery的
load
方法,它会发起GET请求并尝试智能返回纯文本,然后将文本插入到选定的元素中。
wrap
方法则用于在元素内容周围添加标记。
2.1.3 使用
$.get
请求XML数据
<html>
<head>
<title>Loading XML with jQuery</title>
<style type="text/css">
#generated_content {
border: 1px solid black;
width: 300px;
background-color: #dddddd;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.get("animals.xml", function (data) {
var message = "";
var names = data.getElementsByTagName("name");
for (i = 0; i < names.length; ++i) {
message += names[i].firstChild.nodeValue + "<br/>\n";
}
$("#generated_content").html(message);
}, "xml");
});
</script>
</head>
<body>
<p><strong>Ajax parsed XML:</strong></p>
<div id="generated_content"> </div>
</body>
</html>
$.get
方法接收三个参数:请求文件、回调函数和预期数据类型。如果不指定
"xml"
,jQuery会默认选择纯文本。
3. JSON示例
接下来通过一个示例展示如何使用jQuery获取JSON数据。
3.1 输出PHP数组的JSON数据
以下是一个PHP文件
json_example.php
,用于输出JSON数据:
<?php
$animals = array(
"africa" => array("gorilla", "giraffe", "elephant"),
"asia" => array("panda"),
"north america" => array("grizzly bear", "lynx", "orca")
);
print json_encode($animals);
?>
3.2 使用jQuery获取JSON数据
<html>
<head>
<title>Loading JSON with jQuery</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("json_example.php", function (data) {
$.each(data, function (continent, animals) {
var message = "<strong>" + continent + "</strong><br/>";
for (j = 0; j < animals.length; ++j) {
message += animals[j] + ", ";
}
// 移除最后一个逗号和空格
message = message.trim();
message = message.substring(0, message.length - 1);
$("#generated_content").append("<p>" + message + "</p>");
});
});
});
</script>
</head>
<body>
<p><strong>Ajax parsed JSON:</strong></p>
<div id="generated_content"> </div>
</body>
</html>
此示例中,使用
$.getJSON
方法发起请求,通过
$.each
方法遍历JSON对象,将数据显示在页面上。
4. 通过Ajax向PHP脚本发送数据
下面的示例展示了如何通过点击按钮向PHP脚本发送数据,并获取JSON格式的响应。
4.1 PHP脚本
<?php
error_reporting(E_ALL);
$predators = array(
"bear", "shark", "lion", "tiger",
"eagle", "human", "cat", "wolf"
);
$prey = array(
"salmon", "seal", "gazelle", "rabbit",
"cow", "moose", "elk", "turkey"
);
if (isset($_GET['type'])) {
switch ($_GET['type']) {
case "predator":
print json_encode($predators[array_rand($predators)]);
break;
case "prey":
print json_encode($prey[array_rand($prey)]);
break;
default:
print json_encode("n/a");
break;
}
}
?>
4.2 HTML文件
<html>
<head>
<title>Predator/Prey Example</title>
</head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#predator").click(function () {
$("#response").load("predator_prey.php?type=predator");
});
$("#prey").click(function () {
$("#response").load("predator_prey.php?type=prey");
});
});
</script>
<body>
<button id="predator">Predator</button>
<button id="prey">Prey</button>
<p><strong>Ajax response from PHP:</strong></p>
<div id="response"> </div>
</body>
</html>
在这个示例中,点击“Predator”或“Prey”按钮时,会向
predator_prey.php
脚本发送请求,并根据请求参数返回相应的动物名称。
5. 简单图形程序
最后,我们来构建一个简单的绘图应用程序,它由颜色调色板、HTML表格单元格网格和jQuery组成。
<html>
<head>
<title>Drawing Grid Example</title>
<style type="text/css">
#grid, #palette {
padding: 0px;
margin: 0px;
border-collapse: collapse;
}
#palette td, #grid td {
width: 20px;
height: 20px;
}
#grid td {
border: 1px solid #cccccc;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// 10x10网格
for (i = 0; i < 10; ++i) {
$("#grid").append(
"<tr>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"</tr>"
);
}
var active_color = "rgb(0, 0, 0)";
$("#palette td").each(function (index) {
// 绑定点击事件
$(this).bind("click", function () {
active_color = $(this).css("background-color");
$("#debug_palette_color").html("active palette color is: " +
"<span style='width: 20px; height: 20px; background-color:" +
active_color + ";'>" + active_color + "</span>");
});
});
$("#grid td").each(function (index) {
// 绑定点击事件
$(this).bind("click", function () {
$(this).css("background-color", active_color);
});
});
});
</script>
</head>
<body>
<p><strong>Palette</strong></p>
<table id="palette">
<tr>
<td style="background-color: rgb(0, 0, 0);"> </td>
<td style="background-color: rgb(119, 119, 119);"> </td>
<td style="background-color: rgb(255, 255, 255);"> </td>
<td style="background-color: rgb(255, 0, 0);"> </td>
<td style="background-color: rgb(0, 255, 0);"> </td>
<td style="background-color: rgb(0, 0, 255);"> </td>
<td style="background-color: rgb(255, 255, 0);"> </td>
</tr>
</table>
<p><strong>Draw!</strong></p>
<table id="grid" cellspacing="0"></table>
<p><em>Debug console: </em></p>
<div id="debug_palette_color"></div>
</body>
</html>
这个程序通过点击调色板中的颜色,选择活动颜色,然后点击网格单元格,将其背景颜色设置为活动颜色。但目前该程序还不能保存图像,后续将解决这个问题。
总结
本文详细介绍了
XMLHttpRequest
对象的使用,以及如何利用高级JavaScript API(如jQuery)简化开发。同时,通过JSON示例展示了数据交互的方法,并构建了一个简单的图形程序。这些技术在现代Web开发中非常重要,能够实现更流畅的用户体验和高效的数据交互。
流程图
graph TD;
A[开始] --> B[使用XMLHttpRequest];
B --> C[修改页面元素内容];
B --> D[获取XML文件内容];
B --> E[获取HTML文件内容];
B --> F[解析XML特定值];
C --> G[使用高级JavaScript API];
D --> G;
E --> G;
F --> G;
G --> H[jQuery示例];
H --> I[修改<p>元素内容];
H --> J[加载XML纯文本];
H --> K[请求XML数据];
I --> L[JSON示例];
J --> L;
K --> L;
L --> M[输出PHP数组JSON数据];
L --> N[使用jQuery获取JSON数据];
M --> O[通过Ajax向PHP脚本发送数据];
N --> O;
O --> P[简单图形程序];
P --> Q[结束];
表格
| 技术 | 优点 | 示例代码 |
|---|---|---|
| XMLHttpRequest | 实现异步数据交互 | 多个示例代码 |
| jQuery | 简化复杂对象使用,方便跨浏览器支持和DOM操作 | 多个示例代码 |
| JSON | 轻量级数据交换格式 | 示例代码 |
JSON与AJAX的使用指南(续)
6. 图形程序的优化与扩展
在前面构建的简单图形程序基础上,我们可以进一步对其进行优化和扩展,使其具备保存和加载图像的功能。
6.1 保存图像功能的实现
为了实现保存图像的功能,我们需要将当前网格的颜色信息发送到服务器,并将其存储起来。以下是修改后的代码示例:
<html>
<head>
<title>Drawing Grid Example with Save</title>
<style type="text/css">
#grid, #palette {
padding: 0px;
margin: 0px;
border-collapse: collapse;
}
#palette td, #grid td {
width: 20px;
height: 20px;
}
#grid td {
border: 1px solid #cccccc;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// 10x10网格
for (i = 0; i < 10; ++i) {
$("#grid").append(
"<tr>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"</tr>"
);
}
var active_color = "rgb(0, 0, 0)";
$("#palette td").each(function (index) {
// 绑定点击事件
$(this).bind("click", function () {
active_color = $(this).css("background-color");
$("#debug_palette_color").html("active palette color is: " +
"<span style='width: 20px; height: 20px; background-color:" +
active_color + ";'>" + active_color + "</span>");
});
});
$("#grid td").each(function (index) {
// 绑定点击事件
$(this).bind("click", function () {
$(this).css("background-color", active_color);
});
});
// 保存图像按钮点击事件
$("#save_image").click(function () {
var grid_data = [];
$("#grid tr").each(function () {
var row_data = [];
$(this).find("td").each(function () {
row_data.push($(this).css("background-color"));
});
grid_data.push(row_data);
});
$.ajax({
type: "post",
url: "save_image.php",
data: { grid: JSON.stringify(grid_data) },
success: function (response) {
alert("Image saved successfully!");
},
error: function () {
alert("Error saving image!");
}
});
});
});
</script>
</head>
<body>
<p><strong>Palette</strong></p>
<table id="palette">
<tr>
<td style="background-color: rgb(0, 0, 0);"> </td>
<td style="background-color: rgb(119, 119, 119);"> </td>
<td style="background-color: rgb(255, 255, 255);"> </td>
<td style="background-color: rgb(255, 0, 0);"> </td>
<td style="background-color: rgb(0, 255, 0);"> </td>
<td style="background-color: rgb(0, 0, 255);"> </td>
<td style="background-color: rgb(255, 255, 0);"> </td>
</tr>
</table>
<p><strong>Draw!</strong></p>
<table id="grid" cellspacing="0"></table>
<p><em>Debug console: </em></p>
<div id="debug_palette_color"></div>
<button id="save_image">Save Image</button>
</body>
</html>
同时,我们需要创建一个PHP脚本
save_image.php
来处理保存请求:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$grid_data = json_decode($_POST["grid"], true);
// 这里可以将数据保存到文件或数据库中
file_put_contents("saved_image.json", json_encode($grid_data));
echo "success";
}
?>
6.2 加载图像功能的实现
为了实现加载图像的功能,我们需要从服务器获取之前保存的颜色信息,并将其应用到网格中。以下是进一步修改后的代码示例:
<html>
<head>
<title>Drawing Grid Example with Save and Load</title>
<style type="text/css">
#grid, #palette {
padding: 0px;
margin: 0px;
border-collapse: collapse;
}
#palette td, #grid td {
width: 20px;
height: 20px;
}
#grid td {
border: 1px solid #cccccc;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// 10x10网格
for (i = 0; i < 10; ++i) {
$("#grid").append(
"<tr>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"<td> </td>" +
"</tr>"
);
}
var active_color = "rgb(0, 0, 0)";
$("#palette td").each(function (index) {
// 绑定点击事件
$(this).bind("click", function () {
active_color = $(this).css("background-color");
$("#debug_palette_color").html("active palette color is: " +
"<span style='width: 20px; height: 20px; background-color:" +
active_color + ";'>" + active_color + "</span>");
});
});
$("#grid td").each(function (index) {
// 绑定点击事件
$(this).bind("click", function () {
$(this).css("background-color", active_color);
});
});
// 保存图像按钮点击事件
$("#save_image").click(function () {
var grid_data = [];
$("#grid tr").each(function () {
var row_data = [];
$(this).find("td").each(function () {
row_data.push($(this).css("background-color"));
});
grid_data.push(row_data);
});
$.ajax({
type: "post",
url: "save_image.php",
data: { grid: JSON.stringify(grid_data) },
success: function (response) {
alert("Image saved successfully!");
},
error: function () {
alert("Error saving image!");
}
});
});
// 加载图像按钮点击事件
$("#load_image").click(function () {
$.ajax({
type: "get",
url: "load_image.php",
success: function (response) {
var grid_data = JSON.parse(response);
$("#grid tr").each(function (row_index) {
$(this).find("td").each(function (col_index) {
$(this).css("background-color", grid_data[row_index][col_index]);
});
});
},
error: function () {
alert("Error loading image!");
}
});
});
});
</script>
</head>
<body>
<p><strong>Palette</strong></p>
<table id="palette">
<tr>
<td style="background-color: rgb(0, 0, 0);"> </td>
<td style="background-color: rgb(119, 119, 119);"> </td>
<td style="background-color: rgb(255, 255, 255);"> </td>
<td style="background-color: rgb(255, 0, 0);"> </td>
<td style="background-color: rgb(0, 255, 0);"> </td>
<td style="background-color: rgb(0, 0, 255);"> </td>
<td style="background-color: rgb(255, 255, 0);"> </td>
</tr>
</table>
<p><strong>Draw!</strong></p>
<table id="grid" cellspacing="0"></table>
<p><em>Debug console: </em></p>
<div id="debug_palette_color"></div>
<button id="save_image">Save Image</button>
<button id="load_image">Load Image</button>
</body>
</html>
同时,我们需要创建一个PHP脚本
load_image.php
来处理加载请求:
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$grid_data = file_get_contents("saved_image.json");
echo $grid_data;
}
?>
7. 总结与展望
通过本文的介绍,我们深入了解了
XMLHttpRequest
对象的使用,以及如何借助高级JavaScript API(如jQuery)简化开发过程。同时,通过JSON示例展示了数据交互的方法,并构建了一个具备保存和加载功能的简单图形程序。
在未来的Web开发中,这些技术将继续发挥重要作用。随着Web技术的不断发展,我们可以进一步探索更多的优化和扩展方法,例如:
- 优化图形程序的性能,减少加载时间和内存占用。
- 增加更多的绘图工具和功能,如橡皮擦、画笔大小调整等。
- 实现多用户协作绘图,让多个用户可以同时在一个画布上进行绘制。
流程图
graph TD;
A[开始] --> B[简单图形程序];
B --> C[添加保存图像功能];
C --> D[获取网格颜色信息];
D --> E[发送数据到服务器];
E --> F[保存数据到文件或数据库];
C --> G[添加加载图像功能];
G --> H[从服务器获取数据];
H --> I[应用颜色信息到网格];
F --> J[结束];
I --> J;
表格
| 功能 | 实现步骤 | 代码文件 |
|---|---|---|
| 保存图像 | 1. 获取网格颜色信息;2. 发送数据到服务器;3. 服务器保存数据 |
index.html
,
save_image.php
|
| 加载图像 | 1. 从服务器获取数据;2. 应用颜色信息到网格 |
index.html
,
load_image.php
|
超级会员免费看
755

被折叠的 条评论
为什么被折叠?



