jQuery - AJAX get,和post

jQuery get()和post()方法用于通过HTTP GET或POST请求从服务器请求数据.

HTTP请求:GET VS POST

两种在客户端和服务器端进行请求-响应的常用方法是:GET和POST.

·GET---从指定的资源请求数据.

·POST---向指定的资源提交要处理的数据.

GET基本上用于从服务器获得(取回)数据.注释:GET方法可能返回缓存数据.

POST也可以用于从服务器获取数据.不过,POST方法不会缓存数据,并且常用于连同请求一起发送数据.

jQuery $.get()方法

$.get()方法通过HTTP GET请求从服务器上请求数据.

语法:

$.get(URL,callback);

必须的URL参数规定您希望请求的URL.

可选的callback参数是请求成功后所执行的函数名.

下面的例子使用$.get()方法从服务器上的一个文件中取回数据:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml" xml:>
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
 5     <title>jQuery $.get()</title>
 6     <script type="text/javascript" src="js/jquery-1.11.3.js"></script>
 7     <script type="text/javascript">
 8           $(document).ready(function(){
 9                  $('button').click(function() {
10                     $.get('demo_test.php',function(data,status){
11                         alert('数据:'+ data + '\n状态:' + status);
12                     });
13                  });
14           });
15     </script>
16 </head>
17 <body>
18     <button>向页面发送HTTP GET请求,然后获得返回的结果</button>
19 </body>
20 </html>

demo_test.php文件代码:

1 <?php 2 header("Content-type: text/html; charset=utf8"); 3 echo "这是新加载的文字!"; 4 ?>

jQuery $.post()方法

$.post()方法通过HTTP POST请求连同请求一起发送数据.

语法:

$.post(URL,data,callback);

参数

描述

URL

希望请求的URL

data

连同请求发送的数据

callback

请求成功后所执行的函数名

下面的例子使用$.post()连同请求一起发送数据:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml" xml:>
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
 5     <title>jQuery $.post()</title>
 6     <script type="text/javascript" src="js/jquery-1.11.3.js"></script>
 7     <script type="text/javascript">
 8         $(document).ready(function() {
 9             $('button').click(function() {
10                 $.post('demo_test_post.php',{name:"liubeimeng",city:"beijing"},function(data,status){
11                     alert('数据:'+data+'\n状态'+status);
12                 });
13             });
14          });
15     </script>
16 </head>
17 <body>
18     <button>向页面发送 HTTP POST 请求 , 并获得返回的结果 .</button>
19 </body>
20 </html>

demo_test_post.php:

1 <?php
2 $name = $_POST["name"];
3 $city = $_POST["city"];
4 echo "我的名字是:",$name,"我的城市是:",$city;
5 ?>

$.post()的第一个参数是我们希望请求的URL('demo_test_post.php').

然后我们连同请求(name和city)一起发送数据.