1:例子:下面的例子点击按钮会在不更新整个页面的情况下动态更新内容
abcdefg
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<html>
<head>
<script type=
"text/javascript"
src=
"/jquery/jquery.js"
></script>
<script type=
"text/javascript"
>
$(document).ready(
function
(){
$(
"#bt1"
).click(
function
(){
htmlobj=$.ajax({url:
"/jquery/test1.txt"
,async:
false
});
$(
"#myDiv"
).html(htmlobj.responseText);
});
});
</script>
</head>
<body>
<div id=
"myDiv"
>abcdefg</div>
<button id=
"bt1"
type=
"button"
>change abcdefg</button>
</body>
</html>
|
2:通过 AJAX,您的 JavaScript 可使用 JavaScript 的 XMLHttpRequest 对象来直接与服务器进行通信。通过这个对象,您的 JavaScript 可在不重载页面的情况与 Web 服务器交换数据。AJAX 在浏览器与 Web 服务器之间使用异步数据传输(HTTP 请求),这样就可使网页从服务器请求少量的信息,而不是整个页面。
3:应用ajax的步骤:
a:创建XMLHttpRequest对象:variable=new XMLHttpRequest();
老版本的ie5和6使用的是ActiveXObject对象:variable=new ActiveXObject("Microsoft.XMLHTTP");
b:为了应对所有的现代浏览器,必须验证。
var xmlhttp;
if(window.XMLhttpRequest){ xmlhttp= new XMLhttpRequest();}
else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
c:如需要将请求发送到服务器,使用XMLhttpRequest对象的open()和send()方法
xmlhttp.open("get","test.txt",true);
xmlhttp.send();
d:如需获的来自服务器的响应,需使用XMLHttpRequest对象的ResponseText(获取字符串形式的响应数据)和ResponseXML(获取xml形式的响应数据)属性,如果来自服务器的数据不是xml,请使用第一个属性responseText,
可以这样使用:document.getElementById("id").innerHTML=responseText;
如果是xml,则需要解析,js的代码如下:
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
|
<script type=
"text/javascript"
>
function
loadXMLDoc()
{
var
xmlhttp;
var
txt,x,i;
if
(window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=
new
XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=
new
ActiveXObject(
"Microsoft.XMLHTTP"
);
}
xmlhttp.onreadystatechange=
function
(){
if
(xmlhttp.readyState==4 && xmlhttp.status==200)
{ xmlDoc=xmlhttp.responseXML;
txt=
""
;
x=xmlDoc.getElementsByTagName(
"title"
);
for
(i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue +
"<br />"
;
}
document.getElementById(
"myDiv"
).innerHTML=txt;
}
}
xmlhttp.open(
"GET"
,
"/example/xmle/books.xml"
,
true
);
xmlhttp.send();
}
</script>
e:当请求被发送到服务器时,我们需要执行一些基于响应的任务。每当 readyState 改变时,就会触发 onreadystatechange 事件。readyState 属性存有 XMLHttpRequest 的状态信息。下面是 XMLHttpRequest 对象的三个重要的属性:
在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。 当 readyState 等于 4 且状态为 200 时,表示响应已就绪: xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } 4:callback(回调) 函数是一种以参数形式传递给另一个函数的函数。 核心代码:
|