您的位置:首页 > Web前端 > JavaScript

JavaScript的Ajax以及中文乱码问题

2017-08-17 10:43 459 查看
本节实现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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript ajax