Servlet 无法获取jquery ajax post 传过来的数据

J2EE 码拜 9年前 (2015-08-30) 1535次浏览

html:

 <script>

 function getWeather(){

   $.ajax({

   type:”post”,//请求方式

   url:”weather”,//发送请求地址

   data:{//发送给数据库的数据

   province:$(“#province”).val(),

   site:$(“#site”).val()

   }, 

   dataType:”json”,

   success:function(result){

   console.log(result);

    $(“#query”).html(result.value);

   },

   error : function(request, error) {

alert(“”Sorry, some unexpected errors happened. Please contact your system administrator””);

}

   });

   }

  </script>

</head>

<body>

   <h1>天气查询</h1>

   <form   >

          请选择地点:

          <select name=””province”” id=””province”” onChange=””getSite(this.options.selectedIndex)””>

             <option value=””辽宁”” selected=””selected””>辽宁</option>

             <option value=””重庆”” >重庆</option>

          </select>

          <select id=””site”” name=””site””>

             <option value=”大连” selected=””selected””>大连</option>

          </select>

          <input type=”submit” value=”提交” onclick=””getWeather()””>

   </form>

   <div id=””query””></div>

</body>

servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding(“utf-8”);

response.setCharacterEncoding(“gbk”);

String site=request.getParameter(“site”);

String province=request.getParameter(“province”);

WeatherUtil wu=new WeatherUtil();

int provinceCode = wu.getProvinceCode(province);      

                int cityCode = wu.getCityCode(provinceCode, site);       

               List<String> weatherList = wu.getWeather(cityCode); 

               PrintWriter pw=response.getWriter();

              ObjectMapper mapper = new ObjectMapper();

              String result=mapper.writeValueAsString(weatherList);

              pw.write(result);

}

#1
求解
#2
你将form表单的提交方式设置为post试试看
#3

30分

<input type=”submit” value=”提交” onclick=””getWeather()””>  你的按钮的type为submit的时候,会优先提交form,而你的form没有指定method=“post”  所以后台的servlet接收不到post数据

2中解决:

1、将input的标签的type值submit改为button,让他去调用js的ajax方法

2、更改form表单的action属性 和method属性

#4
url:”weather”,//发送请求地址    你确定这个地址能到的?能运行到你指定的servlet的?
#5

回复3楼:

赞同楼上的说法,还有你的地址是不是对的?

#6

回复5楼:

看你在论坛很活跃啊~  

#7

回复6楼:

你咋知道的?

#8

回复7楼:

论坛首页,昨日得分最多的是你…. 你说我知道么… 

#9

回复8楼:

不会吧,我昨天得分最多吗? 多少分?

#10

回复9楼:

论坛首页,发帖按钮的下面有个 论坛标兵

第一个就是你,你的头像太让人记住了

#11

回复10楼:

头像是百度的,我还是第一个,想想我也是醉了,又没啥好处…

#12

回复11楼:

喜欢不,我还有更好的。

#13

回复12楼:

停!  到此截止,别回了 要聊的话,你私聊QQ给我,我加你

#14

回复13楼:

请查收

#15

回复3楼:

按你说的方法解决问题了  谢谢你 

#16

回复5楼:

我的地址应该是没有问题的  因为如果直接在form里 action=‘weather’是可以成功去到后台的  不过通过上面的方法问题就解决了


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Servlet 无法获取jquery ajax post 传过来的数据
喜欢 (0)
[1034331897@qq.com]
分享 (0)