您的位置:首页 > Web前端 > JavaScript

Ajax在静态页面中向指定url发送json请求获取返回的json数据

2016-07-19 10:57 1136 查看
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
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){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","http://www.***.com/web/***/***.json",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>
</body>
</html>


xmlhttp.open("GET","http://www.***.com/web/***/***.json",true);

第一个参数是请求方式,post、get,根据实际情况进行选择。第二个参数是请求的url。第三个参数设置请求是否为异步模式。如果是TRUE,JavaScript函数将继续执行,而不等待服务器响应。

xmlhttp.responseText是返回的数据。

利用document.getElementById("myDiv").innerHTML,将其放至该div块中进行显示。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: