$.post()
方法通过 HTTP POST 方式向服务器发送请求并获取返回的数据。是 $.ajax()
的简化版。
参数讲解:
url:必需。请求地址
data:可选。需要传递到服务器端的参数。 参数形式为“键/值”。
function:可选。发送请求成功后的回调函数,在请求完成时被调用。该函数参数依次为响应体和状态。(只有当Response的返回状态是success才是调用该方法)
type:可选。返回数据的类型。可以是:string或json、xml等类型。
【jsp页面】
|——————————————————
注意,本篇传到后台的参数形式为username=yanshi02&password=123456
|——————————————————
<%@ 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 'post.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="./scripts/jquery-1.7.2.js"></script>
<script type="text/javascript"> var url =""; var queryString = ""; $(function(){ $("input[type='button']").click(function(){ url = $("#editform").attr("action"); //这里需注意,不是serializeArray queryString = $('#editform').serialize(); $.post(url,queryString,function(data){ alert(typeof data+",返回的内容为 "+data); //alert(data.username+","+data.password); //var jsonReturn = this.data; //var jsonReturn = eval("("+data+")"); //var jsonReturn = $.parseJSON(data); var jsonReturn = JSON.parse(data);//将JSON字符串转换为对象 alert(typeof jsonReturn+" 转换后内容 "+jsonReturn); // 解析JSON对象 alert(jsonReturn.username+","+jsonReturn.password); },"json"); }); }); </script>
</head>
<body>
This is my JSP page. <br>
<form id="editform" action="postServlet2" method="post">
<input type="text" name="username" value=""/>
<input type="password" name="password" value=""/>
</form>
<input name="post" type="button" value="提交"/>
</body>
</html>
【后台接收servlet1】
思路:
通过request.getReader
获取一个BufferedReader;
写入到一个StringBulider,转换为String;
……..
返回一个json。
package com.atgui.ajax.app.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
public class PostServlet extends HttpServlet {
/** * Destruction of the servlet. <br> */
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
System.out.println("postServlet destroy() ......");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request,IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
//拿到$("#editform").serialize();
String jsonString =getStringFromReq(request) ;
System.out.println("jsonString..."+jsonString);
//通过拿到的querystring转换为map
HashMap<String,Object> map = getMapFromQueryString(jsonString);
//将转换得到的map转换为json并返回
ObjectMapper objectMapper = new ObjectMapper();
String resultJson = objectMapper.writeValueAsString(map);
//此处直接返回JSON object对象,JSP可直接使用data.key
System.out.println("resultJson ..."+resultJson);
// resultJson = resultJson.replace("\"","\\\"");
// resultJson = "\""+resultJson+"\"";
//此处返回JSON 字符串 string对象;JSP需要解析才能使用data.key
// System.out.println("resultJson ..."+resultJson);
out.print(resultJson);
out.flush();
out.close();
}
public void init() throws ServletException {
// Put your code here
System.out.println("postServlet init().......");
}
public String getStringFromReq(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = request.getReader();
char[]buff = new char[1024];
int len;
while((len = reader.read(buff)) != -1) {
sb.append(buff,0,len);
}
}catch (IOException e) {
e.printStackTrace();
}
String resultString = sb.toString();
return resultString;
}
public HashMap<String,Object> getMapFromQueryString(String queryString) {
HashMap map = new HashMap<String,String>();
String[] qStrings = queryString.split("&");
for (String string : qStrings) {
String[] qStrings2 = string.split("=");
map.put(qStrings2[0],qStrings2[1]);
}
return map;
}
}
postServlet init().......
jsonString...username=admin&password=123456
resultJson ...{"username":"admin","password":"123456"}
resultJson ..."{\"username\":\"admin\",\"password\":\"123456\"}"
下图标明:
响应内容类型为json;
请求类型为默认值;
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
会将参数以 "a=1"&"b=2";的形式进行编码。
如:username=yanshi02&password=123456
表单数据在Form Data域;
【特别提醒】
//将转换得到的map转换为json并返回
ObjectMapper objectMapper = new ObjectMapper();
String resultJson = objectMapper.writeValueAsString(map);
//此处直接返回JSON object对象,JSP可直接使用data.key
System.out.println("resultJson ..."+resultJson);
- 拿到返回的data
//将转换得到的map转换为json并返回
ObjectMapper objectMapper = new ObjectMapper();
String resultJson = objectMapper.writeValueAsString(map);
//此处直接返回JSON object对象,JSP可直接使用data.key
System.out.println("resultJson ..."+resultJson);
// resultJson = resultJson.replace("\"","\\\"");
// resultJson = "\""+resultJson+"\"";
//此处返回JSON 字符串 string对象;JSP需要解析才能使用data.key
// System.out.println("resultJson ..."+resultJson);
- 拿到返回的数据【string形式】
- 解析为json object
【后台接收servlet2】
思路:
通过Map<String,String[]> map=request.getParameterMap();
得到参数;
…….
返回json。
package com.atgui.ajax.app.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
public class PostServlet2 extends HttpServlet {
/** * request.getParameterMap(); */
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
System.out.println("postServlet2 destroy() ......");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,response);
}
public void doPost(HttpServletRequest request,IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
Map<String,String[]> map = request.getParameterMap();
HashMap<String,Object> map2 = new HashMap<String,Object>();
for(String key : map.keySet()){
// System.out.println("key :"+key+",value : "+map.get(key)[0]);
// if (map.get(key).length>1) {
// System.out.println("key :"+key+",value :"+map.get(key)[1]);
// }
for (int i = 0; i < map.get(key).length; i++) {
System.out.println("key :"+key+","+i+","+map.get(key)[i]);
}
map2.put(key,map.get(key)[0]);
}
//拿到$("#editform").serialize();
// String jsonString =getStringFromReq(request) ;
// System.out.println("jsonString..."+jsonString);
//通过拿到的querystring转换为map
// HashMap<String,Object> map = getMapFromQueryString(jsonString);
//将转换得到的map转换为json并返回
ObjectMapper objectMapper = new ObjectMapper();
String resultJson = objectMapper.writeValueAsString(map2);
System.out.println("resultJson1: "+resultJson);
//如下,进行手动拼接!!!如果不拼接,JSP可以直接使用data.key获取json属性
resultJson = resultJson.replace("\"","\\\"");
resultJson = "\""+resultJson+"\"";
System.out.println("resultJson ..."+resultJson);
// "{\"username\":\"admin\",\"password\":\"123456\"}"
out.print(resultJson);
out.flush();
out.close();
}
public void init() throws ServletException {
// Put your code here
System.out.println("postServlet2 init().......");
}
}
result as follows:
postServlet2 init().......
key :username,admin
key :password,123456
resultJson1: {"username":"admin",\"password\":\"123456\"}"
【这里讲述一下手动拼接后JSP解析过程,如果没有手动拼接,那么为上述特别提醒中第二种方式】
- JSP 拿到后台传回的data
- 进行解析为JSON 对象
【后台接收Servlet3】
思路:
直接使用request.getParameter();
获取字符串;
手动拼接为JSON字符串直接返回。
package com.atgui.ajax.app.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
public class PostServlet5 extends HttpServlet {
/** * queryString = $('#editform').serialize(); 使用request.getParameter() */
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
System.out.println("postServlet destroy() ......");
}
public void doGet(HttpServletRequest request,IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
String password = request.getParameter("password");
String jsonString ="{\"username\":"+'"'+name+'"'+",\"password\":"+'"'+password+'"'+"}";
//手动拼接JSON如上形式,可直接返回,此时json为string非object;如果再次使用ObjectMapper转换,JSP 将最终按其字符数组对象进行单个字符遍历!!!
System.out.println("jsonString..."+jsonString);
//{"username":"admin","password":"123456"}
ObjectMapper objectMapper = new ObjectMapper();
String resultJson = objectMapper.writeValueAsString(jsonString);
System.out.println("resultJson ..."+resultJson);
//"{\"username\":\"admin\",\"password\":\"123456\"}"
response.reset();
out.println(jsonString );
out.flush();
out.close();
}
public void init() throws ServletException {
// Put your code here
System.out.println("postServlet5 init().......");
}
}
此时String jsonString 返回的 json type 为string ,需要进行解析为object 才能使用 data.key 获取json属性。。。过程参考上面。
一定要分清,虽然JS里面一切皆为对象,但是 typeof :string 与 typeof :object 不是一回事!!!
但是如果你使用 instance of object,那么 string 或者object 都会返回true!
题外话1:
如果以以下形式传值呢?
$.post(url+"querystring="+queryString,function(data){});
一部分参数在URL后面,一部分为form data。
【如果为 get 请求,无论传输形式怎样,数据都在Query String Parameters 里面!】点击查看Get 请求
F12看控制台:
(1) 请求URL:
Request URL:http://localhost:8080/AJAX/postServlet2?querystring=username=yanshi02&password=123456
(2) URL后面的参数放在了Query String Parameters里面。
而且,分成的两部分:
querystring:username=yanshi02
password:123456
//默认以 & 分割 !!!
(3) 另外正常传的queryString放在了Form Data里面。
其中,接收方法思路有三种。
① 使用request.getParameterMap
;
getParameterMap 会把键值对参数,解析为对应map 的key:value !
Map<String,map.get(key)[0]);
}
result as follows :
postServlet2 init().......
key :querystring,username=yanshi02
key :username,yanshi02
key :password,123456
key :password,1,123456
resultJson ...{"username":"yanshi02","querystring":"username=yanshi02","password":"123456"}
//可见 key为password的数组:"password":["123456","123456"]
② 使用request.getReader ;
只能获取 Form Data,不能获取Query String Data。
同理,该方法不适用 $.get() 。
③ 使用request.getQueryString
;
只能获取Query String Data,不能获取Form Data 。
题外话2
如果请求形式为:
queryString = $('#editform').serialize();
$.post(url,{mydata:queryString},function(data){});
首先看大图:
数据传输形式为:
mydata:username=yanshi02&password=123456
那么除了上述前两种思路外。
还有第三种思路!
使用request.getParameter("mydata")
String jsonStr = request.getParameter("mydata");
System.out.println(jsonStr);
只要获得拼接的string,就可以返回json!
综上:
默认ContentType下,数据会以username=yanshi02&password=123456
形式进行编码。
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
如果是以{key : value} 形式传输的,有三种接收思路:
如$.post(url,function(data){});
① 使用request.getReader
;
② 使用request.getParameterMap
;
③ 使用request.getParameter("key")
;
如果是以 value形式传输的,则可以使用前两种思路。
如$.post(url,function(data){});
如果使用第三种思路,则需要将获取得到的string手动拼接为json string
注意 :此时的queryString取值!
queryString = $('#editform').serialize();
至于queryString取如下值(JSON形式),请看下一篇queryString为json形式
【http://www.jb51.cc/article/p-eplduxhq-bpe.html】
queryString = $('#editform').serializeArray();//object
queryString = JSON.stringify(queryString);//string
原文链接:https://www.f2er.com/ajax/161441.html