第6章 AJAX

第6章 AJAX
AJAX-Asynchronous JavaScript and XML 异步javascript和xml
6.1 基于请求加载数据(从Web服务器上取得静态的数据文件)
1 追加html

1 $(document).ready(function(){
2   $('#letter-a a').click( function(){
3   $(#dictionary).load('a.html',function(){
4     //回调函数:加载完a.html后做什么
5     alert('Loaded!');
6   }); 
7   return false;
8   });
9 });

把一个html片加载到匹配元素内。这个片段必须是适合这个匹配元素的。

2 操作javaScript对象
javascript对象就是由一些“键-值”对组成的,而且可以方便的用花括号来定义,另一方面javascript的数组可以使用方括号进行动态定义。这两种语法组合起来,可以表达复杂且庞大的数据结构,这就是JSON(javascript object notation,javascript对象表示法).

[
{
"key":"value1",
"key 2":["array",
"of",
"items"]
}
{
"key":"value2",
"key 2":["array",
"of",
"items"]
}
]

取得这些数据,用$.getJSON()方法,这个方法会在取得相应的文件后对文件进行处理并将处理得到的javascript对象提供给代码。

 1 $(document).ready(function(){
 2 $('#letter-b a').click( function(){
 3 $.getJSON('b.json', function( data ){
 4 //回调函数:加载完b.json后做什么?
 5 /*加载b.json返回一个javascript对象data --例子是个javascript对象数组对象
 6 利用全局函数$.each()来处理这个data对象.
 7 该函数以一个数组或映射作为第一个参数,以一个回调函数作为第二个参数;
 8 另外,将每次循环中数组或映射的当前索引和当前项作为回调函数的两个参数
 9 */
10 $.each(data, function(entryIndex,entry){
11 var html = '<div class="entry">';
12 html += '<h3 class="term">'+ entry['term']+ '</h3>';
13 html += '</div>';
14 $('#dictionary').append(html);
15 });
16 });
17 return false;
18 });
19 });

3 执行脚本
页面初次加载时就取得所需的全部的javascript也是没有必要的。可以按需动态加载.js文件。这如加载一个html片段一样简单。

1 $(document).ready( function(){
2 $('#letter-c a').click( function(){
3 $.getScript('c.js');//前面的例子是需要回调函数来处理结果数据以便有效利用加载的文件,但对于脚本文件来说是自动执行!
4 return false;
5 });
6 });

4 加载XML文档

 1 $(document).ready(function(){
 2 $('#letter-b a').click( function(){
 3 //$.get()函数只是简单取得由URL指定的文件,然后将纯文本格式的数据提供给回调函数,但根据服务器提供的MIME类型知道响应的是XML的情况下,提供给回调函数的将是XML DOM树--jquery的DOM遍历对XML文档就如同对HTML文档一样
 4 $.get('d.xml',function(data){
 5 //加载完xml文件后,怎么处理?
 6 $(data).find('entry:has(quote[author])').each( function(){
 7 var $entry = $(this);
 8 var html = '<div class="entry">';
 9 html += '<h3 class="term">' + $entry.attr('term');+'</h3>';
10 html += '</div>';
11 $('#dictionary').append($(html));
12 });
13 });
14 return false;
15 });
16 });

6.2 选择数据格式
上面4种尾部数据的格式,每种都可以通过jquery本地的AJAX函数加以处理。在用户请求它时,而不是请求之前,才将信息加载到现有的页面上!
HTML片段:直接添加到现有页面中无需遍历数据,连回调函数都不必使用。但不易重用,因为这种外部文件与它们的目标容器(即现有页面)必须紧密结合。
JSON文件:其结果是它很方便重用,必须通过遍历来提取相关信息,再将信息呈现到页面上。
JavaScript文件:它不是一种真正的数据存储机制。这种文件针对特定的语言,所以不能通过它们将同样的信息提供给完全不同的系统。
XML文档:可移植性强。以这种格式提供数据使它极有可能在其他地方被重用。不过,XML格式的文件体积相对较大,同其他文件格式相比解析和操作它们的速度要慢一些。

6.3 向服务器传递参数
1 执行GET请求
从浏览器发送到服务器参数,服务器端脚本根据该参数提取相应的数据。
e.php

 1 <?php
 2 $entries = array(
 3 'EAVESDROP' => array(
 4 'part'=>'v.i.',
 5 'definition'=>'secretly to overhear a catalogue of the crimes and vices of another or yourself',
 6 'author'=>'Gopete Sherany',
 7 ),
 8 ....
 9 );
10 $term = strtoupper($_REQUEST['term']);
11 if( isset($enties[$term])){
12 $entry = $entries[$term];
13 $html = '<div class="entry">';
14 $html .= '<h3 class="term">';
15 $html .= $term;
16 $html .= '</h3>';
17 $html .= '<div class="part">';
18 $html .= $entry['part'];
19 $html .= '</div>';
20 $html .= '</div>';
21 print($html);
22 }
23 ?>
 1 $(document).ready( function(){
 2 $('#letter-e a').click( function(){
 3 //注意第二个参数是一个用来构建查询字符串的键和值的映射
 4 $.get('e.php',{'term':$(this).text()}, function(data){
 5 //回调函数,对取得的e.php?term=***的结果数据data进行处理
 6 $('#dictionary').html(data);
 7 });
 8 return false;
 9 });
10 });

2 执行POST请求

GET请求是把参数放在作为URL一部分的查询字符串中,而POST不是。GET方法对面传输的数据量有限制。

1 $(document).ready( function(){
2 $('#letter-e a').click( function(){
3 $.post('e.php',{'term':$(this).text()}, function(data){
4 $('#dictionary').html(data);
5 });
6 return false;
7 });
8 });

使用.load()方法还可以简化这些代码,它接受到映射参数时会默认使用POST方法发送请求:

1 $(document).ready( function(){
2 $('#letter-e a').click( function(){
3 $('#dictionary').load('e.php',{'term':$(this).text()});
4 return false;
5 });
6 });

3 序列化表单
常规的表单提交机制会在整个浏览器窗口中加载响应。而使用jquery的ajax工具箱则能异步地提交表单,并将响应放到当前页面中。

f.php

 1 foreach($entries as $term => $entry){
 2 if(strpos($term,strtoupper($_REQUEST['term'])) != FALSE){
 3 $html = '<div class="entry">';
 4 $html .= '<h3 class="term">';
 5 $html .= $term;
 6 $html .= '</h3>';
 7 $html .= '<div class="part">';
 8 $html .= $entry['part'];
 9 $html .= '</div>';
10 $html .= '</div>';
11 print($html);
12 }
13 }
 1 $(document).ready( function(){
 2 $('#letter-f form').submit( function(){
 3 //通过名称属性逐个搜索输入字段并将该字段的值添加到映射中
 4 $('#dictionary').load('f.php',{'term':$('input[name="term"]').val()});
 5 return false;
 6 });
 7 });
 8 
 9 $(document).ready( function(){
10 $('#letter-f form').submit( function(){
11 //将匹配的DOM元素转换成能够随AJAX请求传递的查询字符串???
12 $.get('f.php',$(this).serialize(), function(data){
13 $('#dictionary').html(data);
14 });
15 return false;
16 });
17 });

使用JSONP加载远程数据

JSONP的格式是把标准JSON文件包装在一对圆括号中,圆括号又前置一个任意字符串。这个字符串即所谓的P(Padding,填充),由请求数据的客户端来决定。而且,由于有一对圆括号,返回的数据在客户端可能会导致一次函数调用或者是为某个变量赋值--取决于客户端请求中发送的填充字符串。
g.php

 1 <?php
 2 $data = '
 3 [
 4 {
 5 "term": "GALLOWS",
 6 "part": "n.",
 7 "definition": "A stage for the performance of miracle plays, in which the leading actor is translated to heaven. In this country the gallows is chiefly remarkable for the number of persons who escape it.",
 8 "quote": [
 9 "Whether on the gallows high",
10 "Or where blood flows the reddest,",
11 "The noblest place for man to die —",
12 "Is where he died the deadest."
13 ],
14 "author": "Old play"
15 },
16 ...
17 ]
18 ';
19 print($_GET['callback'].'('.$data.')');
20 ?>

eg.

jsonp1336466439850(
[
{
"term": "GALLOWS",
"part": "n.",
"definition": "A stage for the performance of miracle plays, in which the leading actor is translated to heaven. In this country the gallows is chiefly remarkable for the number of persons who escape it.",
"quote": [
"Whether on the gallows high",
"Or where blood flows the reddest,",
"The noblest place for man to die —",
"Is where he died the deadest."
],
"author": "Old play"
},
...
]
)
 1 $(document).ready(function() {
 2 var url = 'http://examples.learningjquery.com/jsonp/g.php';
 3 $('#letter-g a').click(function() {
 4 $.getJSON(url + '?callback=?', function(data) { //http://examples.learningjquery.com/jsonp/g.php?callback=jsonp1336469221109&_=1336469224885
 5 $('#dictionary').empty();
 6 $.each(data, function(entryIndex, entry) {
 7 var html = '<div class="entry">';
 8 html += '<h3 class="term">' + entry['term']
 9 + '</h3>';
10 html += '</div>';
11 $('#dictionary').append(html);
12 });
13 });
14 return false;
15 });
16 });

部分加载HTML页面

1 $(document).ready(function() {
2 $('#letter-h a').click(function() {
3 $('#dictionary').load('h.html .entry');//指定了选择符表达式,则load()会利用它查找加载文档的匹配部分
4 return false;
5 });
6 });
原文地址:https://www.cnblogs.com/zhyryxz/p/2490461.html