JavaScript的Ajax以及中文乱码问题

本文介绍了一种使用 JavaScript 的 Ajax 技术实现前端与后台数据交互的方法,并解决了中文乱码的问题。通过示例代码展示了如何从前端发送数据到后台,并由后台处理后再返回前端显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本节实现js的Ajax前台传送文字,后台接收并打印然后将受到的文字传到前台并提示的过程。
在写这段代码的时候遇到了乱码问题,解决方案是:在tomcat 的server.xml文件中

<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

加上URIEncoding=”UTF-8”
问题解决
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()
{
    //创建XMLHttpRequest 对象或者ActiveX 对象
    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){
                }
        }
    }
    var account = "大大";
    //使用open方法,第三个参数不写默认true即默认异步
    xmlrequest.open("POSt",'http://localhost:8080/showUsers/Ajax?account='+account,true);   
    //发送请求,先有open再有send后台才能接收
    xmlrequest.send();
    //监视函数,(onreadystatechange )存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
    //当readyState 返回4为请求已完成,且响应已就绪,
    //当status 返回200 servlet响应正确
    xmlrequest.onreadystatechange = function processResponse(){
        //响应完成
        if(xmlrequest.readyState == 4){
            //响应正常
            if(xmlrequest.status == 200){
                var head = xmlrequest.responseText;
                alert(head);
            }
        }
    };
}
</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 {
        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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值