Ajax的实现方式
原生js实现步骤
Jquery实现方式
原生js实现
步骤
1:判断浏览器引擎对象
2:建立连接
3:发送请求
4:接收并处理来自服务器的响应结果
HTML页面代码:
<!DOCTYPE html
>
<html lang
="en">
<head>
<meta charset
="UTF-8">
<title>Ajax 原生js实现方式
</title
>
<script>
function
fun() {
var xmlhttp
;
if (window
.XMLHttpRequest
)
{
xmlhttp
=new XMLHttpRequest();
}
else
{
xmlhttp
=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp
.open("GET","ajaxServlet?uname=jack",true);
xmlhttp
.send();
xmlhttp
.onreadystatechange
=function(){
if (xmlhttp
.readyState
==4 && xmlhttp
.status
==200){
var v
= xmlhttp
.responseText
;
alert(v
);
}
}
}
</script
>
</head
>
<body>
<button value
="使用原生js请求数据" onclick
="fun()">使用原生js请求数据
</button
>
</body
>
</html
>
AjaxServlet:
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req
, HttpServletResponse resp
) throws ServletException
, IOException
{
resp
.setContentType("text/html;utf-8");
req
.setCharacterEncoding("UTF-8");
String name
= req
.getParameter("uname");
resp
.getWriter().println("hello "+name
);
}
@Override
protected void doPost(HttpServletRequest req
, HttpServletResponse resp
) throws ServletException
, IOException
{
doGet(req
,resp
);
}
}
Jquery实现方式
转载请注明原文地址: https://lol.8miu.com/read-29201.html