首页 > 网站 > WEB开发 > 正文

AJAX - $.post(url,data,function,type)-3

2024-04-27 15:18:32
字体:
来源:转载
供稿:网友

上一篇http://blog.csdn.net/J080624/article/details/54949134讲解到如果传到后台的参数为:

queryString = $('#editform').serializeArray();//objectqueryString = JSON.stringify(queryString);//string $.post(url,{mydata:queryString},function(data){ });

如果形式为$.post(url,queryString,function(data){}); 呢,后台如何接收?

就像第一篇所讲解的那样,使用request.getReader。。。从而获取String!

【后台接收方法】

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 PostServlet4 extends HttpServlet { /** * queryString = $('#editform').serializeArray(); queryString = JSON.stringify(queryString);//string */ 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, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); //拿到$("#editform").serialize(); String jsonString =getStringFromReq(request) ; System.out.println("jsonString..."+jsonString); ObjectMapper objectMapper = new ObjectMapper(); String resultJson = objectMapper.writeValueAsString(jsonString); 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; }}

result as follows :

//初始化servletpostServlet init().......//读取到的stringjsonString...[{"name":"username","value":"yanshi02"},{"name":"passWord","value":"123456"}]//返回jsonresultJson ..."[{/"name/":/"username/",/"value/":/"yanshi02/"},{/"name/":/"password/",/"value/":/"123456/"}]"

题外话:

为什么不使用request.getParameterMap?

因为这里传输的为JSON数组字符串,没有username=yanshi02&password=123456 的形式!不能拆解为 key :value !!!

如下所示为使用 request.getParameterMap

key :[{"name":"username","value":"yanshi02"},{"name":"password","value":"123456"}]value:
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表