jsp使用jquery ajax提交表单失效。没反应。

代码:index.jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript" src="BAO/jquery-3.3.1.min.js" charset="gb2312"></script> <script type="text/javascript"> $(document).ready(function(){ $("a").click(function(){ alert("请求成功"); $.ajax({ url:'FormServlet', type:'post', data:$("#myform").serialize(), cache:false, dataType:'json', success:function(data){ alert("请求成功"); } }); }); $("button").click(function(){ $("#div1").html("lalala"); }); }); </script> </head> <body> <div id="div1"><h2>使用 jQuery AJAX 修改文本内容</h2></div><button>获取其他内容</button> <form action="" id="myform"> 用户名<input type="text" name="username"/> 密码<input type="password" name="password"/> 性别<input type="radio" name="sex" value="男人">man <input type="radio" name="sex" value="女人">woman </form> <a href="#" style="text-decoration: none;">使用ajax提交表单数据</a> </body></html>Servlet.java代码如下(我只修改了doPost):public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String userName = request.getParameter("username"); String passWord = request.getParameter("password"); String sex = request.getParameter("sex"); System.out.println("name:"+userName+"==pass:"+passWord+"==sex:"+sex); }在测试时,唯独ajax无效,这是为什么,可以的话,请告诉我怎么修改代码,实现功能。

说明提交失败了呀。

    检查$.ajax({url: ...}) 这个url是否是正确的能访问的。是否存在跨域。

    $('a').click(function(e) {  e.preventDefault() }) e.preventDefault() 清除掉默认事件

追问

测试了一下,是URL没法正确访问,但要怎么该才能访问FormServlet呢?

我是新手,求帮忙。

温馨提示:答案为网友推荐,仅供参考