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

通过 PHP、XML 和 jQuery 实现即时性(4)
迁移到 XML第一种方式是使用 XML 作为您从服务器到客户端的传输语法。此处的想法是服务器提供一个通用 XML 端点,任何流程都可以使用该端点来执行查询,并且您的客户端足够智能,能够读取 XML 并以其想要的方式来格式化它。
要变成 XML,首先要创建如 中所示的新服务器页面。
清单 6. XML Ajax 页面1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| <?php
include 'Simpsons.php';
header( 'Content-type: text/xml' );
$s = new Simpsons();
$doc = new DOMDocument();
$root = $doc->createElement( 'episodes' );
$doc->appendChild( $root );
foreach( $s->find( $_REQUEST['q'] ) as $episode ) {
$el = $doc->createElement( 'episode' );
$el->setAttribute( 'title', $episode['title'] );
$el->setAttribute( 'episode', $episode['episode'] );
$el->setAttribute( 'season', $episode['season'] );
$el->setAttribute( 'aired', $episode['aired'] );
$tn = $doc->createTextNode( $episode['summary'] );
$el->appendChild( $tn );
$root->appendChild( $el );
}
print $doc->saveXML();
?>
|
虽然搜索仍然一样,但是您格式化结果的方式变了。现在,该代码创建了 XML 文档并将节点附加到其上,从而保存所有返回的数据。然后在脚本的末尾,它只是将 XML DOM 保存为字符串。请注意在脚本的顶部,在导出 XML 而非 HTML 时,还要将内容类型设置为文本/xml。
如果在您的 web 浏览器中导航到此页面,则您会看到类似 中的情况。
图 4. XML 响应页面 不过,一些浏览器可能以更结构化的方式显示已返回的文本。如果您想查看原始的源 XML,则您可以选择 View - Source 以便看到类似 中的窗口。
图 5. XML 响应页面源代码 如您所见,该脚本创建了一些良好格式化的 XML,准备好供新的客户端代码使用。
解析 XML(而不是直接使用 HTML)的新客户端代码位于 中。
清单 7. 使用 XML 的即时搜索页面1
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
30
31
32
| <html><head>
<script src="jquery-1.4.2.min.js"></script>
<link rel="stylesheet" href="styles.css" type="text/css" />
<title>Instant Search - XML Based</title>
</head>
<body>
Simpsons Search: <input type="text" id="term" />
<table id="results">
</table>
<script>
$(document).ready( function() {
$('#term').keyup( function() {
$.get('search_xml.php?q='+escape($('#term').val()), function(data) {
html = '<table id="results">';
$(data).find('episode').each( function() {
var ep = $(this);
html += '<tr><td class="episode"><b>'+
ep.attr('title')+'</b> ';
html += 'Season '+ep.attr('season')+' ';
html += 'Episode '+ep.attr('episode')+' ';
html += 'Aired '+ep.attr('aired')+'</td></tr>';
html += '<tr><td class="summary">'+
ep.text()+'</td></tr>';
} );
html += '</html>';
$('#results').replaceWith( html );
} );
} );
} );
</script>
</body>
</html>
|
用于监控击键和发出 Ajax 请求的客户端代码几乎完全一样。所不同的是不同的 URL 获取 XML 数据而不是 HTML 数据。
在数据返回以后,该代码使用 jQuery 来寻找所有剧集标签。然后它可格式化大量 XML 并使用 replaceWith 函数来用新表替换旧表。由于使用了 jQuery,此代码比在使用浏览器的原生 DOM 功能时更容易使用。
传输数据的另一种方式是通过 JSON(JavaScript 对象符号)。 |
|
|
|
|
|