jquery $.post【2014-11-10】

jQuery.post()


jQuery.post( url [, data ] [, success ] [, dataType ] )Returns:jqXHR

Description: Load data from the server using a HTTP POST request.

  • version added:1.0jQuery.post( url [, data ] [, success ] [, dataType ] )

    • url
      Type: String
      A string containing the URL to which the request is sent.
    • //解释一下:URL是必选的参数,其余参数可选。URL是request请求的路径。
    • data
      A plain object or string that is sent to the server with the request.
    • //解释一下:data是浏览器通过request请求向服务器发送一些参数,这个参数的类型可以是字符串类型,也可是plainObject类(感觉和Java中Object差不多)。
    • success
      Type: Function( Object data,String textStatus,jqXHR jqXHR )
      A callback function that is executed if the request succeeds. Required ifdataType is provided, but can be null in that case.
    • //解释一下:success是request请求成功后触发的回调函数。
    • dataType
      Type: String
      The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
    • //解释一下:dataType是从服务器返回的类型,可以是XML、json、script、text、HTML。

This is a shorthand Ajax function, which is equivalent to:

1
2
3
4
5
6
7
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});

The success callback function is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response. It is also passed the text status of the response.

//解释一下:上面的$.post可以用$.ajax来替代。

As of jQuery 1.5, the success callback function is also passed a"jqXHR" object (injQuery 1.4, it was passed the XMLHttpRequest object).

Most implementations will specify a success handler:

1
2
3
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});

This example fetches the requested HTML snippet and inserts it on the page.

Pages fetched with POST are never cached, so thecache and ifModified options in jQuery.ajaxSetup() have no effect on these requests.

//解释一下:自从jQuery1.5后是用的jqXHR 对象,而以前的版本是用的XMLHttpRequest对象。通过post方法获取的数据不会缓存。

The jqXHR Object

As of jQuery 1.5, all of jQuery‘s Ajax methods return a superset of theXMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by$.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (seeDeferred object for more information). ThejqXHR.done() (for success), jqXHR.fail() (for error), andjqXHR.always() (for completion, whether success or error) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see thejqXHR Object section of the $.ajax() documentation.

The Promise interface also allows jQuery‘s Ajax methods, including$.get(), to chain multiple .done(), .fail(), and.always() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});

//解释一下:向example.php发送请求如果成功就弹出success,如果发送两次都成功了,就弹出second success;如果失败,弹出error;如果完成,弹出finished等。这里的done就是请求成功后执行的函数,fail就是请求失败后执行的函数,always就是无论请求成功还是失败都要执行的函数。

Deprecation Notice

The jqXHR.success(), jqXHR.error(), andjqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, usejqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

//解释一下:success、error和complete方法是在jQuery1.5中出现的,现在不推荐使用,推荐用done、fail、always来代替这些函数。

Additional Notes:

  • Due to browser security restrictions, most "Ajax" requests are subject to thesame origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
  • If a request with jQuery.post() returns an error code, it will fail silently unless the script has also called the global.ajaxError() method. Alternatively, as of jQuery 1.5, the.error() method of the jqXHR object returned by jQuery.post() is also available for error handling.
  • //解释一下:由于浏览器的安全策略,来自不同的域,子域、端口和协议时,获取数据可能不成功。

Examples:

Example: Request the test.php page, but ignore the return results.

1
$.post( "test.php" );

Example: Request the test.php page and send some additional data along (while still ignoring the return results).

1
$.post( "test.php", { name: "John", time: "2pm" } );

Example: Pass arrays of data to the server (while still ignoring the return results).

1
$.post( "test.php", { ‘choices[]‘: [ "Jon", "Susan" ] } );

Example: Send form data using ajax requests

1
$.post( "test.php", $( "#testform" ).serialize() );

Example: Alert the results from requesting test.php (HTML or XML, depending on what was returned).

1
2
3
$.post( "test.php", function( data ) {
alert( "Data Loaded: " + data );
});

Example: Alert the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).

1
2
3
4
$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});

Example: Post to the test.php page and get content which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>).

1
2
3
4
$.post( "test.php", { func: "getNameAndTime" }, function( data ) {
console.log( data.name ); // John
console.log( data.time ); // 2pm
}, "json");

//解释一下:上面是post方法的一些简单举例,涉及的东西还是上面讲到的。

Example: Post a form using ajax and put results in a div

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search...">
<input type="submit" value="Search">
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
// Attach a submit handler to the form
$( "#searchForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
term = $form.find( "input[name=‘s‘]" ).val(),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( url, { s: term } );
// Put the results in a div
posting.done(function( data ) {
var content = $( data ).find( "#content" );
$( "#result" ).empty().append( content );
});
});
</script>
</body>
</html> //解释一下:post的一个实例,这里只给出了前台页面的jQuery实现。

下面是我写的一个简单的实例(Struts+jQuery实现):

所需jar包:

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ajax</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
   <filter>  
        <filter-name>struts2</filter-name>  
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>struts2</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
</web-app>

struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE struts PUBLIC  
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
    "http://struts.apache.org/dtds/struts-2.0.dtd">  
  
<struts>  
  
    <package name="ajax" extends="json-default" namespace="/">  
        <action name="ajaxLogin" class="action.AjaxLoginAction" method="execute">  
            <result type="json">  
                <param name="root">result</param>  
            </result>  
        </action>  
    </package>  
  
</struts>  




前台页面(index.jsp):

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>ajax</title>
		<script type="text/javascript" src="js/jquery1.11.1.js">
		</script>
		<script type="text/javascript">
			$(document).ready(function(){
				$("#btn_login").click(function(){
					$.ajax({
	                    type:"post",
	                    url:"ajaxLogin",//需要用来处理ajax请求的action
	                    dataType:"json",//设置需要返回的数据类型
	                    data:{
	                    	loginName:$("#loginName").val(),
							loginPwd:$("#loginPwd").val()
	                    },
	                    success:function(data){
	                        var d = eval("("+data+")");//将数据转换成json类型,可以把data用alert()输出出来看看到底是什么样的结构
	                        //得到的d是一个形如{"key":"value","key1":"value1"}的数据类型,然后取值出来
	                         
	                        $("#result").html("ajax"+d.name+" "+d.pwd);
	                         
	                    },
	                    error:function(){
	                        alert("系统异常,请稍后重试!");
	                        $("#result").html("ajax error");
	                    }//这里不要加","
	                });
	            });
				$("#btn_post").click(function(){
					var params = {loginName:$("#loginName").val(),
							loginPwd:$("#loginPwd").val()};
					$.post(
	                    "ajaxLogin",//需要用来处理ajax请求的action
	                    params,
	                    function s(data){
	                        var d = eval("("+data+")");//将数据转换成json类型,可以把data用alert()输出出来看看到底是什么样的结构
	                        //得到的d是一个形如{"key":"value","key1":"value1"}的数据类型,然后取值出来
	                         
	                        $("#result").html("ajax"+d.name+" "+d.pwd);
	                    }
	                );
	            });
			});
		</script>
	</head>
	<body>
      	<span>用户名:</span>  
        <input type="text" id="loginName" name="loginName">  
        <br />  
  
        <span>密码:</span>  
        <input type="password" name="loginPwd" id="loginPwd">  
        <br />  
  
        <input type="button" id="btn_login" value="Login" />  
        <input type="button" id="btn_post" value="post" />  
        <p>  
                                    这里显示ajax信息:  
            <br />  
            <span id="result"></span>  
        </p>  
</body>
</html>

Action代码:

package action;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import com.opensymphony.xwork2.ActionSupport;

public class AjaxLoginAction extends ActionSupport
{
	private static final long serialVersionUID = 1L;
	
	private String result;
	private String loginName;
	private String loginPwd;
	
	public String getResult()
	{
		return result;
	}
	public void setResult(String result)
	{
		this.result = result;
	}
	public String getLoginName()
	{
		return loginName;
	}
	public void setLoginName(String loginName)
	{
		this.loginName = loginName;
	}
	public String getLoginPwd()
	{
		return loginPwd;
	}
	public void setLoginPwd(String loginPwd)
	{
		this.loginPwd = loginPwd;
	}
	
	public String execute()
	{
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", this.loginName);
		map.put("pwd", this.loginPwd);
		JSONObject jo = JSONObject.fromObject(map);
		this.result = jo.toString();
		System.out.println("==============================");
		System.out.println(result);
		System.out.println("==============================");
		
		return SUCCESS;
	}
	
}

//解释一下:这里实现了post和Ajax两种方法的实现,大家可以对比一下。



如有错误,请指出!谢谢!


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。