首页 > Web开发 > 详细

利用ajax向jsp传输数据

时间:2016-06-18 12:50:33      阅读:144      评论:0      收藏:0      [点我收藏+]

ajax代码

var obtn=document.getElementsByTagName(‘input‘)[0];
obtn.onclick=function () {
var xhr=null;
try{
xhr=new XMLHttpRequest();
}catch(e){
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}

//第一种方法用get get 中由于要编码可以用encodeURI(‘刘伟‘)但是不知道为什么出来是问号就在后台想把编码转好了,然后还要注意get中由于会出现缓存的问题,可以随时加个随机数,就是new Date()当时间当做随机数
/*xhr.open(‘get‘,‘send.jsp?name=‘+‘刘伟‘+‘&date=30&‘+new Date().getTime(),true);
xhr.send();*/

//第二种方法是post方法,没有缓存也不用编码
xhr.open(‘post‘,‘send.jsp‘,true);
xhr.setRequestHeader(‘content-type‘, ‘application/x-www-form-urlencoded‘);
xhr.send(‘name=刘伟&date=30‘);
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
alert(xhr.responseText);
}}}}

jsp后台

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<html><body>
<%

String name=request.getParameter("name");
String date=request.getParameter("date");
//转换成一个字节数组,利用iso-8859-1编码  注意这里!因为编码后才能够解决前台输出中文乱码的额问题。
name = new String(na.getBytes("iso-8859-1"),"UTF-8"); //把name转为utf-8编码
out.println("姓名"+name);
out.println("时间"+date);
%>
</body></html>

利用ajax向jsp传输数据

原文:http://www.cnblogs.com/Guoguomix/p/5595931.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!