2013年9月4日 星期三

jquery-post

inf : http://api.jquery.com/jQuery.post/


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
5
$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="http://code.jquery.com/jquery-1.9.1.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>

沒有留言:

張貼留言