JavaScript使用Ajax传送JSON数据

2 篇文章 0 订阅

Ajax.jsp代码

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Ajax</title>
<script type="text/javascript">

function loadXMLDoc()
{
    var xmlrequest;
    if(window.XMLHttpRequest){
        xmlrequest = new XMLHttpRequest();
    }else if(window.ActiveXObject){
        try{
            xmlrequest = new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            try{
                xmlrequest = new ActiveXObject("Microsoft.XMLHTTP");
            }catch(e){
                }
        }
    }
//创建json对象
//JSON 值可以是:
//数字(整数或浮点数)
//字符串(在双引号中)
//逻辑值(true 或 false)
//数组(在方括号中)
//对象(在花括号中)
//null
    var json ={"name":"張三","password":"123"}
    //将json数据转换成字符串方便传递
    var account=JSON.stringify(json);
    xmlrequest.open("POSt",'http://localhost:8080/showUsers/Ajax?account='+account+'',true);
    //设置请求头

    //发送请求
    xmlrequest.send(account);
    xmlrequest.onreadystatechange = function processResponse(){
        //响应完成
        if(xmlrequest.readyState == 4){
            //响应正常
            if(xmlrequest.status == 200){
            //接收json字符串
                var head = xmlrequest.responseText;
                //将字符串转化成json数据格式
                var json1=JSON.parse(head);         
                //调用json数据中属性   
                alert(json1.password);
            }
        }
    };
}
</script>
</head>
<body>
<div id="myDiv"><h3>Let AJAX change this text</h3></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
<%=request.getParameter("account") %>
</body>
</html>

Ajax.java代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Object account = request.getAttribute("account");
        String account=request.getParameter("account");
        System.out.println(account);
        response.setContentType("text/html;charset=UTF-8");
        request.setAttribute("account", account);
        PrintWriter writer = response.getWriter();
        writer.write(account);
        writer.flush();
        writer.close();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值