- 使用Ajax
- 基础:请求并显示静态TXT文件
- 字符集编码
- 缓存、阻止缓存
- 动态数据:请求js(或json)文件
- eval的使用
- DOM创建元素
- 局部刷新:请求并显示部分网页文件
Ajax:不刷新页面去服务器上读取、刷新数据,让js读取服务器上的数据。
第一个function是读取成功返回的数据。第二个function是读取失败返回的数据。
<script>
window.onload=function(){
var oBtn=document.getElementById('btn1');
oBtn.onclick=function(){
ajax('http://localhost/Ajax/aaa.txt',function(str){
alert(str)
},function (){
alert('失败');
})
}
}
</script>
</head>
<body>
<input type="button" value="读取" id="btn1"/>
</body>
http://localhost/Ajax/read_txt.html 在浏览器上显示的网址一定是localhost这种形式的。而不是file:///D:/material/wamp/www/Ajax/read_txt.html、
- 缓存:只有第一次开它的时候才是请求服务器,以后都是从本地的缓存中读。
- 取消缓存
出现的问题:我们在.txt文件中修改内容之后,点击获取.txt中的内容,浏览器还是不显示出来修改之后的内容。这种情况IE尤其严重,必须关过浏览器才可以。尤其是股票信息等一些常变的东西更需要取消缓存。所以,我们需要取消缓存。
缓存是根据url来缓存的,只要url一直改变,就不会缓存了。localhost/Ajax/aaa.txt?a=9. ?后面的a=9是get数据,不管a=12还是a=5,对内容是没有影响的。
//取消缓存
oBtn.onclick=function(){
ajax('http://localhost/Ajax/aaa.txt?t='+new Date().getTime(),function(str){
alert(str)
},function (){
alert('失败');
})
}
<script>
window.onload=function(){
var oBtn=document.getElementById('btn1');
oBtn.onclick=function(){
ajax('http://localhost/Ajax/arr.txt?t='+new Date().getTime(),function(str){
alert(str)//返回的是字符串
},function (){
alert('失败');
})
}
}
</script>
</head>
<body>
<input type="button" value="读取" id="btn1"/>
</body>
使用eval()解析:可以把字符串变成数组。
<script>
window.onload=function(){
var oBtn=document.getElementById('btn1');
oBtn.onclick=function(){
ajax('http://localhost/Ajax/arr.txt?t='+new Date().getTime(),function(str){
var arr=eval(str)
alert(arr[2])//3
},function (){
alert('失败');
})
}
}
</script>
json:
<script>
window.onload=function(){
var oBtn=document.getElementById('btn1');
oBtn.onclick=function(){
ajax('http://localhost/Ajax/arr2.txt?t='+new Date().getTime(),function(str){
//arr2.txt中的内容[{a:5,b:7},{a:8,b:12}]
var arr=eval(str)
alert(arr[0])//object
alert(arr[0].a)//5
},function (){
alert('失败');
})
}
}
</script>
</head>
<body>
<input type="button" value="读取" id="btn1"/>
</body>
读取json数据:
<script>
window.onload=function(){
var oBtn=document.getElementById('btn1');
var oUl=document.getElementById('ul1');
oBtn.onclick=function(){
ajax('http://localhost/Ajax/data.txt?t='+new Date().getTime(),function(str){
//data.txt中的内容[{user:'张三',pass:'123456'},{user:'李四',pass:'12'},{user:'王五',pass:'56'}]
var arr=eval(str)
for(var i=0;i<arr.length;i++){
var oLi=document.createElement('li');
oLi.innerHTML='用户名:<strong>'+arr[i].user+'</strong> 密码:<span>'+arr[i].pass+'</span>';
oUl.appendChild(oLi);
}
},function (){
alert('失败');
})
}
}
</script>
</head>
<body>
<input type="button" value="读取" id="btn1"/>
<ul id="ul1">
</ul>
</body>
Ajax原理:
HTTP请求方法:
- GET——用于获取数据(如:浏览帖子)
- POST——用于上传数据(如:用户注册)
- GET和POST区别
- get方式就是把数据放入到url中 (通过网址、容量小、安全性差、有缓存)
- post方式http Content (不通过网址、容量大、安全性好一点、没有缓存)
<body>
<form action="http://www.zhinengshe.com/" method="get">
用户名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="提交"/>
</form>
</body>