通过 PHP、XML 和 jQuery 实现即时性(5)
 
- UID
- 1066743
|

通过 PHP、XML 和 jQuery 实现即时性(5)
迁移到 JSON在 Web 2.0 的世界中,JSON 是一种非常流行的移动数据的方式。它小巧、方便、快捷,便于浏览器读取,因为需要做的所有操作就是评估已返回的 JavaScript 代码。创建 JSON 也很简单,就如您在 中的 Ajax 搜索页面的 JSON 版本中所见的那样。
清单 8. JSON Ajax 页面1
2
3
4
5
6
7
8
| <?php
include 'Simpsons.php';
header( 'Content-type: application/json' );
$s = new Simpsons();
print json_encode( $s->find( $_REQUEST['q'] ) );
?>
|
您只需使用 json_encode 函数来将已返回的数组转变为 JSON 代码。如果您好奇的话,这里也存在一个可将 JSON 转回为 PHP 基本类型的 json_decode 函数。大多数流行语言都具有与这里一样简单的 JSON 机制,可以将基本数据结构转化为 JSON,或者转换出 JSON。
如果您在浏览器中查看 JSON 页面,则您会看到类似 中的响应页面。
图 6. JSON 响应页面 虽然本页面可能不会太吸引人们的目光,但是对于浏览器中的 JavaScript 解译器来说,此页面看起来非常易于阅读。
用于读取 JSON 格式化输出的相应的即时 UI web 代码位于 中。
清单 9. JSON 即时搜索 UI1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| <html><head>
<script src="jquery-1.4.2.min.js"></script>
<link rel="stylesheet" href="styles.css" type="text/css" />
<title>Instant Search - JSON Based</title>
</head>
<body>
Simpsons Search: <input type="text" id="term" />
<table id="results">
</table>
<script>
$(document).ready( function() {
$('#term').keyup( function() {
$.get('search_json.php?q='+escape($('#term').val()), function(data) {
html = '<table id="results">';
$.each( data, function( ind, ep ) {
html += '<tr><td class="episode"><b>'+ep.title+'</b> ';s
html += 'Season '+ep.season+' ';
html += 'Episode '+ep.episode+' ';
html += 'Aired '+ep.aired+'</td></tr>';
html += '<tr><td class="summary">'+ep.summary+'</td></tr>';
} );
html += '</html>';
$('#results').replaceWith( html );
} );
} );
} );
</script>
</body>
</html>
|
此代码非常类似于 XML 代码,不同的是您可以对返回的数组使用 jQuery each 函数,然后使用点符号来访问数据中的所有重要关键字(也就是说,标题、剧集、摘要等等)。
现在您具有:可以用作您自己的工作起始点的即时搜索功能的初步实现。 |
|
|
|
|
|