温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Ajax提交数据

发布时间:2020-06-18 22:42:42 来源:网络 阅读:502 作者:Adam的blog 栏目:开发技术

1,jsp

<title>测试Ajax</title> <script type="text/javascript" src="jquery-1.10.1.js"></script> <script type="text/javascript"> $(function(){ $("#xxx").blur(function(){ var value = $('#xxx').val(); $.ajax({ url:"/java_web02/AjaxServlet", //要请求服务器的url data:{val:value}, //这是一个对象,表示请求参数val=xx, 服务器端可以使用request.getParameter()来获取 async:true, //是否为异步请求 cache:false, //是否缓存结果 type:"POST", //请求方式 dataType:"json", //服务器返回的数据是什么类型 success:function(result){//这个函数在服务器执行成功时会被调用,参数result就是服务器返回的值 $('label').text(result.name + "," + result.age); } }); }); }); </script> </head> <body> 用户名:<input type="text" name="name" id="xxx"/><label></label><br /> 年龄:<input type="text" name="age" /> </body>

2,servlet

@WebServlet("/AjaxServlet") public class AjaxServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置编码格式 request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //获取前台传来的数据 String value = request.getParameter("val"); if(value.equals("xiaoxiao")){ String str = "{\"name\":\"好人\", \"age\":23}"; //用\来转义 response.getWriter().print(str); }else { String str = "{\"name\":\"坏人\", \"age\":89}"; response.getWriter().print(str); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI