ajax请求也可以用form表单向后台提交数据!!!!
激动的我简直语无伦次,不说了上代码,用ajax实现form表单数据的请求,啦啦啦啦
html:
<form> <input name="userName" value="yyl"/> <input name="gender" value="F"/> </form>
ajax:
$(function (){ $.ajax({ url : "<%=request.getContextPath()%>/myTestFn.do?method=myAjax", type : "post", dataType : "json", data : $("#form").serialize(), success : function (data){ alert("name:"+data.name); }, error:function(){ alert("error"); } }); });
java:
package com.ulic.misp.newSaleWxProduct.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ulic.misp.pub.framework.log.Log; import com.ulic.misp.pub.framework.log.LogFactory; import com.ulic.misp.pub.util.JacksonUtils; import com.ulic.misp.wx.controller.BaseController; /** * @author v_yinyl * @date 2018-9-26 下午4:40:36 * @version 18.2B */ public class MyMonthCotroller extends BaseController { private final Log log = LogFactory.getLog(MyMonthCotroller.class); public void myAjax(HttpServletRequest request, HttpServletResponse response) throws Exception { log.info("11111111111"); String name = request.getParameter("userName"); String gender = request.getParameter("gender"); Map<String ,String> map = new HashMap<String, String>(); map.put("name",name); map.put("gender",gender); response.getWriter().println(JacksonUtils.toJson(map)); return; } }
不知道为什么,一直演示不成功,这让我非常难受......
2018/09/26
nndt,终于演示成功了,
排查步骤:1,ajax的书写是否正确 $.ajax({ }); 2,java代码中接收数据的属性与form里面的name属性是否一致 3,检查ajax请求的方法(myAjax)是否被拦截
,4,发现步骤1和步骤二都没有问题,但是请求ajax的时候还是error,那么重建controller,问题就解决了,其实一点也不神奇因为
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
上面这两个路径才是HttpServletRequest;HttpServletResponse;的正确路径,导错的话,整个controller都不能正常使用
拓展:
import org.springframework.web.servlet.ModelAndView;
ModelAndView的路径如果导错也不能正常访问页面
if you want to go fast,go alone,if you want to go far,go together