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

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

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

$.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"); queryString = $('#editform').serialize(); $.post(url,queryString,function(data){ alert(data); //var jsonReturn=eval("("+data+")"); } ,"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, HttpServletResponse response) throws ServletException, 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); 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; }}

下图标明:

响应内容类型为json; 请求呢欧让类型为默认值;

Content-Type:application/x-www-form-urlencoded; charset=UTF-8会将参数以 "a=1"&"b=2";的形式进行编码。如:username=yanshi02&password=123456

表单数据在Form Data域;

这里写图片描述


【后台接收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 { /** * Destruction of the servlet. <br> */ 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, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, 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]); for (int i = 0; i < map.get(key).length; i++) { System.out.println(i+","+map.get(key)[i]); } map2.put(key, map.get(key)[0]); } //将转换得到的map2转换为json并返回 ObjectMapper objectMapper = new ObjectMapper(); String resultJson = objectMapper.writeValueAsString(map2); System.out.println("resultJson ..."+resultJson); 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, value : yanshi020,yanshi02key :password, value : 1234560,123456resultJson ...{"username":"yanshi02","password":"123456"}

题外话1: 如果以以下形式传值呢?

$.post(url+"querystring="+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=yanshi02password:123456//默认以 & 分割 !!!

(3) 另外正常传的queryString放在了Form Data里面。

这里写图片描述

其中,接收方法思路有三种。

① 使用request.getParameterMap;

修改部分代码 :

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]); }

result as follows :

postServlet2 init().......key :querystring,0,username=yanshi02key :username,0,yanshi02key :password,0,123456key :password,1,123456resultJson ...{"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,{mydata:queryString},function(data){});

① 使用request.getReader; ② 使用request.getParameterMap; ③ 使用request.getParameter("key");

如果是以 value形式传输的,则可以使用前两种思路。

$.post(url,queryString,function(data){});

注意 :此时的queryString取值!

queryString = $('#editform').serialize();

至于queryString取如下值(JSON形式),请看下一篇queryString为json形式 【http://blog.csdn.net/J080624/article/details/54949134】

queryString = $('#editform').serializeArray();queryString = JSON.stringify(queryString);//string
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表