ajax傳值後臺獲取初步瞭解
阿新 • • 發佈:2019-02-18
後臺程式碼如下前臺頁面程式碼如下: <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% 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="index.js"></script> <script src="<c:url value='/ajax/jquery-2.1.4.js'/>"></script> <script type="text/javascript"> function add() { /** 當給個錯誤的url的時候,就會走到error方法裡面, 該ajax請求會返回一個status code碼,當返回值為200時,表示成功,執行success方法,否則執行error方法; */ /** 採用json的方式進行資料傳遞 */ var jsonvalue = { "name" : document.getElementById("input1").value, "id" : 1, "password" : document.getElementById("mima").value, }; alert("走到了add方法裡面"); /** dataType : "json":的意思是從後臺返回的值必須為json格式,否則將執行error方法 */ $.ajax({ cache : true, type : "post", url : "<c:url value='/testForcode'/>", data : { "ss" : JSON.stringify(jsonvalue) }, async: false, error : function(request) { alert("提交失敗"); }, success : function(data) { alert("data:" + data); $("#div1").text(data); } }); } </script> </head> <body> <form id="form1"> 使用者名稱:<input type="text" id="input1" name="username" id="yonghu"></input><br /> 密碼:<input type="password" name="password" id="mima"></input><br /> <input type="button" name="提交" value="提交" onclick="add()"></input> <div id="div1"></div> </form> </body> </html>
response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); /** * 接受從前端傳遞過來的json資料,要注意引入解析json的包 */ String name=request.getParameter("ss"); System.out.println(name); JSONObject json=JSONObject.fromObject(name); Iterator iter = json.keySet().iterator(); Map<String,String> map = new HashMap<String,String>(); /** * 解析來自前端頁面的值,解析json陣列 */ while (iter.hasNext()) { String key = (String) iter.next(); String value = json.getString(key); System.out.println("key:"+key+",value:"+value); map.put(key, value); } Map jmap = com.alibaba.fastjson.JSON.parseObject(name); Map mjmap = new HashMap(); for(Object obj:jmap.keySet()){ mjmap.put(obj, jmap.get(obj)); } System.out.println(mjmap); /** * 前端頁面設定了dataType為json格式,則後臺返回時返回的格式必須為json格式 */ out.print("提交成功"); out.flush(); out.close(); }