ajax教程

ajax的使用步骤

javascript版本

1.创建一个XMLHttpRequest对象

var xhr=new XMLHttpRequest()
document.write(xhr)

2.设置响应函数

xhr.onreadystatechange=checkFunction
function checkFunction(){ 
	document.write(xhr.responseText)
}

3.设置并发出请求

url="http://localhost:8080/HelloController/hello"
xhr.open("GET",url,true)
xhr.send(null)

此时会出现一个错误:Access to XMLHttpRequest at 'http://localhost:8080/HelloController/hello' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.由于我用的是springMVC此时只要在controller上添加一个允许跨域的注解即可。

jquery版本

<!DOCTYPE html>
<html>
<head>
	<title>jquery ajax 教程</title>
	<meta charset="utf-8">
</head>
<body>
	<div>
		<button id="ajaxbuttonid">
			ajax按钮
		</button>
		<div id=responsedivid>
		</div>
	</div>
</body>
<script type="text/javascript" src="./jquery-3.6.0.min.js">
	
</script>
<script type="text/javascript">
	$(document).ready(function(){
		$("#ajaxbuttonid").click(function(){
			responseCon=$.ajax({url:"http://localhost:8080/HelloController/hello",async:false})
			console.log(responseCon["responseText"])
			$("#responsedivid").html(responseCon["responseText"])
		})
	})
</script>
</html>

 


版权声明:本文为weixin_50277857原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。