需要掌握:ajax
ajax原生写法
需要 web服务器
<script type="text/javascript">
function get(url){
// XMLHttpRequest对象用于在后台与服务器交换数据
var xhr=new XMLHttpRequest();
xhr.open('GET',url,false);
xhr.onreadystatechange=function(){
// readyState == 4说明请求已完成
if(xhr.readyState===4){
if(xhr.status===200){ // 响应成功
console.log(xhr.responseText);// 打印响应数据
}
}
}
xhr.send();
}
get("1.json")
</script>
优化写法
function get(url,success){
// XMLHttpRequest对象用于在后台与服务器交换数据
var xhr=new XMLHttpRequest();
xhr.open('GET',url,false);
xhr.onreadystatechange=function(){
// readyState == 4说明请求已完成
if(xhr.readyState===4){
if(xhr.status===200){ // 响应成功
console.log(xhr.responseText);// 打印响应数据
// 字符串类型的json转成 对象,之后就可以访问{}对象属性的方式
const res = JSON.parse(xhr.responseText)
success( res )
}
}
}
xhr.send();
}
例子
<button id="login">登录</button>
<div id="box" class="warn"></div>
document.getElementById("login").addEventListener("click",function(e){
get("js/2loginFails.json",function( data ){
console.log("data 的类型:",typeof data)
console.log("code:",data.code)
if(data.code != 0){
document.getElementById("box").innerHTML = data.msg
}
})
})