主入口
导入必要的库
准备工作
@app.route('/content/')
def content():
return render_template('content.html')
@app.route('/xhr/')
def xhr():
return render_template('xhr.html')
content.html中的内容为纯文本 ‘test ajax’
xhr.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax</title>
</head>
<body>
<h1>xhr请求</h1>
<div id="msg"></div>
<button onclick="">显示内容</button>
##点击显示内容的按键后将content页面中的内容显示到div中
</body>
</html>
<script>
function getData() {
var xhr; ##声明一个变量
##通过winsow对象判断浏览器版本实例化xhr
if (window.ActiveXObject) {
xhr=new ActiveXObject('Microsoft.XHLHttp');
}
else if (window.XMLHttpRequest){
xhr= new XMLHttpRequest();
}
else{
throw new Error('不支持ajax');
}
##指定xhr状态变化关联事件
##onreadystatechange请求状态改变事件句柄
##xhr.readyState 0 没有发送;1 已打开;2 已接受headers;3 正在载入;4 搞定
##xhr.status 200 正常;3XX 重定向;4XX 客户端问题;5XX 服务器端问题
##responseText服务器响应文本 1 html;2 json;3 text
##responseXML服务器响应XML
##response服务器整个响应
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200){
document.getElementById('msg').innerHTML=xhr.responseText;
}
}
xhr.open('GET','/content/'); ##初始化请求方式与地址
xhr.send(); ##发送请求
}
</script>