原生AJAX请求的示例

先准备一个servlet来接受ajax请求

package cn.zsp.servlet;

import cn.zsp.pojo.Person;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AjaxServlet extends BaseServlet{

    protected void javaScriptAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        System.out.println("请求过来了");
        Person person=new Person(1,"鹏哥");
//        需要先转成json格式的字符串
        Gson  gson =new Gson();
        String s = gson.toJson(person);
        resp.getWriter().write(s);
    }
}

在html里的jsp模块里调用ajax请求

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="pragma" content="no-cache" />
		<meta http-equiv="cache-control" content="no-cache" />
		<meta http-equiv="Expires" content="0" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Insert title here</title>
		<script type="text/javascript">
			//在这里使用javaScript语言发起Ajax请求
			function ajaxRequest() {
// 				1、我们首先要创建XMLHttpRequest 
				var 	xmlHttpRequest=new XMLHttpRequest();
// 				2、调用open方法设置请求参数
				xmlHttpRequest.open("GET","http://localhost:8080/json_ajax/ajaxServlet?action=javaScriptAjax",true);
// 				4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。
				xmlHttpRequest.onreadystatechange=function () {
					if (xmlHttpRequest.status==200 &&xmlHttpRequest.readyState==4)
					{
						var  jsonObj=JSON.parse(xmlHttpRequest.responseText);
						document.getElementById("div01").innerHTML= "编号是"+jsonObj.id+"名字是"+jsonObj.name;
					}
				}
// 				3、调用send方法发送请求
				xmlHttpRequest.send();
//
			}
		</script>
	</head>
	<body>	
		<button onclick="ajaxRequest()">ajax request</button>
		<div id="div01">
		</div>
	</body>
</html>```

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值