利用ajax向jsp传输数据

本文介绍了一种使用AJAX与JSP进行前后端数据交互的方法,包括GET和POST请求方式的具体实现及注意事项。GET请求需考虑URL编码与缓存问题,而POST请求则更为安全且无需考虑编码问题。

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

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>

转载于:https://www.cnblogs.com/Guoguomix/p/5595931.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值