jquery AJAX應用

load(url[,data][,callback])------------->通常用來從WEB服務器上獲取靜態的數據文件
url: string類型 請求HTML頁面的URL地址
data(可選): object 發送至服務器的key/value數據
callback(可選):function 請求完成時回調函數


例子:
主頁面代碼:

<style type="text/css">
* { margin:0; padding:0;}
body { font-size:12px;}
.comment { margin-top:10px; padding:10px; border:1px solid #ccc;background:#DDD;}
.comment h6 { font-weight:700; font-size:14px;}
.para { margin-top:5px; text-indent:2em;background:#DDD;}
</style>



  $(function(){
      $("#send").click(function(){
              $("#resText").load("test.html .para",function (responseText, textStatus, //test.html .para爲test.html中.class爲para的內容XMLHttpRequest){
                         alert( $(this).html() );    //在這裏this指向的是當前的DOM對象,即 $("#iptText")[0]
                         alert(responseText);       //請求返回的內容
                         alert(textStatus);            //請求狀態:success,error
                         alert(XMLHttpRequest);     //XMLHttpRequest對象
            });
      })
  })

<input type="button" id="send" value="Ajax獲取" />

<div  class="comment">
    已有評論:
</div>
<div id="resText" ></div>


test.html中的代碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div class="comment">
 <h6>張三:</h6>
 <p class="para">沙發.</p>
</div>
<div class="comment">
 <h6>李四:</h6>
 <p class="para">板凳.</p>
</div>
<div class="comment">
 <h6>王五:</h6>
 <p class="para">地板.</p>
</div>
</body>
</html>


傳遞方式
load()方法的傳遞方式根據蠶食data來自動指定。
如果沒有參數傳遞,則採用GET方式傳遞;
反之,就會自動轉換爲POST方式

load的回調函數爲function (responseText, textStatus,XMLHttpRequest))
responseText:請求返回的內容
textStatus:請求狀態:success/error/notmodified/timeout4種狀態
XMLHttpRequest://XMLHttpRequest對象



$.get()使用異步GET方式來進行異步請求
$.get(url[,data][,callback][,type])
url:請求的頁面的URL
data(可選) object 發送服務器的Key/value數據會作爲QueryString附加到請求URL中
callback(可選) function 載入成功時回調函數(只有當Response的返回狀態爲success才返回此函數)
type : string 服務器返回的內容的格式,包括xml/html/script/json/text和_default


<div id="resText" >


    $(function(){
       $("#send").click(function(){
            $.get("get1.php", {
                        username :  $("#username").val() ,
                        content :  $("#content").val() 
                    }, function (data, textStatus){
                        $("#resText").html(data); // 把返回的數據添加到頁面上
                    }
            );
       })
    })

而get1.php中的代碼
echo "<div class='comment'><h6>{$_REQUEST['username']}:</h6><p class='para'>{$_REQUEST['content']}</p></div>";


$(function(){
 $("#send").click(function(){
 $("#resText").load("get1.php?username="+$('#username').val()+"&content="+$('#content').val());
 //如果是中文需要編碼
 })
 })

如果返回的類型是XML類型則要在異步的界面head文件裏
header("Content-Type:text/html; charset=utf-8");//PHP
但是XML文檔類型體積大和難以解析。
資源:http://json.org 瞭解JSON



例子:
 $("#send").click(function(){
 $.get("get3.php", {
 username : $("#username").val() ,
 content : $("#content").val()
 }, function (data, textStatus){
 var username = data.username;
 var content = data.content;
 var txtHtml = "<div class='comment'><h6>"+username+":</h6><p class='para'>"+content+"</p></div>";
 $("#resText").html(txtHtml); // 把返回的數據添加到頁面上
 },"json");
 })

get3.php
<?php
    header("Content-Type:text/html; charset=utf-8");
    echo "{ username : /"{$_REQUEST['username']}/" , content : /"{$_REQUEST['content']}/"}"
?>



$.post()
POST請求則是作爲HTTP消息的實體內容發送給WEB服務器
GET方式對傳輸的數據有大小限制(通常不能大於2KB)
POST方式傳遞的數據量要比GET方式大得多(理論上不受限制)

GET方式請求的數據會被瀏覽器緩存起來,而其他人可以從瀏覽器的歷史記錄中讀取到這些數據
在某種情況下,get方式會帶來嚴重的安全性問題,而POST方式相對於來說就可以避免這些問題


例子:
 $(function(){
 $("#send").click(function(){
 $.post("post1.php", {
  username : $("#username").val() ,
  content : $("#content").val()
  }, function (data, textStatus){
  $("#resText").html(data); // 把返回的數據添加到頁面上
  }
   );
   })
   })

post1.php
<?php
    header("Content-Type:text/html; charset=utf-8");
    echo "<div class='comment'><h6>{$_REQUEST['username']}:</h6><p class='para'>{$_REQUEST['content']}</p></div>";
?>


例子2:
 $(function(){
  $("#send").click(function(){
  $.post("post2.php", {
  username : $("#username").val() ,
  content : $("#content").val()
  }, function (data, textStatus){
  var username = $(data).find("comment").attr("username");
   var content = $(data).find("comment content").text();
   var txtHtml = "<div class='comment'><h6>"+username+":</h6><p class='para'>"+content+"</p></div>";
   $("#resText").html(txtHtml); // 把返回的數據添加到頁面上
   },"xml");
   })
   })

post2.php
<?php
    header("Content-Type:text/xml; charset=utf-8");
    echo "<?xml version='1.0' encoding='utf-8'?>".
         "<comments>".
         "<comment username='{$_REQUEST['username'] }' >".
         "<content>{$_REQUEST['content']}</content>".
         "</comment>".
         "</comments>";
?>

例子3:
 $(function(){
  $("#send").click(function(){
  $.post("post3.php", {
  username : $("#username").val() ,
  content : $("#content").val()
  }, function (data, textStatus){
  var username = data.username;
   var content = data.content;
   var txtHtml = "<div class='comment'><h6>"+username+":</h6><p class='para'>"+content+"</p></div>";
   $("#resText").html(txtHtml); // 把返回的數據添加到頁面上
   },"json");
  })
  })

post3.php
<?php
    header("Content-Type:text/html; charset=utf-8");
    echo "{ username : /"{$_REQUEST['username']}/" , content : /"{$_REQUEST['content']}/"}"
?>

$.getScript()
有時候,在頁面初次加載時就取得所需的全部JavaScript文件時完全沒有必要。
$.getScript()來加載.js文件

 $(function(){
  $('#send').click(function() {
  $.getScript('test.js');//加載後自動執行JS
  });
  })

test.js內容爲:
var comments = [
  {
    "username": "張三",
    "content": "沙發."
  },
  {
    "username": "李四",
    "content": "板凳."
  },
  {
    "username": "王五",
    "content": "地板."
  }
];

  var html = '';
  $.each( comments , function(commentIndex, comment) {
      html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
  })

  $('#resText').html(html);

例子:
<style type="text/css">
* { margin:0; padding:0;}
body { font-size:12px;}
.comment { margin-top:10px; padding:10px; border:1px solid #ccc;background:#DDD;}
.comment h6 { font-weight:700; font-size:14px;}
.para { margin-top:5px; text-indent:2em;background:#DDD;}
.block{width:80px;height:80px;background:#DDD;}
</style>



 $(function(){
  $.getScript('http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js',function(){
  $("<p>加載JavaScript完畢</p>").appendTo("body");
  $("#go").click(function(){
  $(".block").animate( { backgroundColor: 'pink' }, 1000)
  .animate( { backgroundColor: 'blue' }, 1000);
  });
   });
   })

//jquery.color.js爲jQuery官方顏色插件

<button id="go">運行</button>
<div class="block"></div>


$.getJSON()

 $(function(){
  $('#send').click(function() {
  $.getJSON('test.json', function(data) {
  $('#resText').empty();
  var html = '';
  $.each( data , function(commentIndex, comment) {
  html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
  })
   $('#resText').html(html);
   })
  })
  })

test.json
[
  {
    "username": "張三",
    "content": "沙發."
  },
  {
    "username": "李四",
    "content": "板凳."
  },
  {
    "username": "王五",
    "content": "地板."
  }
]


例子2:
   $(function(){
        $('#send').click(function() {
            $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=car&tagmode=any&format=json&jsoncallback=?",
                      function(data){
                          $.each(data.items, function( i,item ){
                                $("<img class='para'/> ").attr("src", item.media.m ).appendTo("#resText");
                                if ( i == 3 ) {
                                    return false;
                                }
                          });
                     }
            );
       })
   })


http://api.flickr.com/services/feeds/photos_public.gnetags=car&tagmode=any&format=json&jsoncallback=?
得到的內容:
({
        "title": "Recent Uploads tagged car",
        "link": "http://www.flickr.com/photos/tags/car/",
        "description": "",
        "modified": "2010-01-26T16:13:42Z",
        "generator": "http://www.flickr.com/",
        "items": [
       {
            "title": "Hwy 395 4",
            "link": "http://www.flickr.com/photos/adrianjm/4306207627/",
            "media": {"m":"http://farm5.static.flickr.com/4058/4306207627_b555857078_m.jpg"},
            "date_taken": "2010-01-26T11:13:42-08:00",
            "description": "<p><a href=/"http://www.flickr.com/people/adrianjm//">adrianjm<//a> posted a photo:<//p> <p><a

href=/"http://www.flickr.com/photos/adrianjm/4306207627//" title=/"Hwy 395 4/"><img src=/"http://farm5.static.flickr.com/4058/4306207627_b555857078_m.jpg/"

width=/"240/" height=/"160/" alt=/"Hwy 395 4/" /><//a><//p> <p>This area of the 395 (not much further north than photos Hwy 395 photos 1 and 2) is significantly

greener and flatter than that of North Eastern California. <br /> <br /> Really enjoyable drive. Clear, blue skies, and nice scenery. The road was diverse enough so

that you never got bored.<//p>",
            "published": "2010-01-26T16:13:42Z",
            "author": "[email protected] (adrianjm)",
            "author_id": "59761920@N00",
            "tags": "from road trip car oregon shot south hwy eastern 395"
       },
       {
            "title": "Parade car __D_09-12-07",
            "link": "http://www.flickr.com/photos/pamelasag61/4306947712/",
            "media": {"m":"http://farm5.static.flickr.com/4011/4306947712_0a94f2fd05_m.jpg"},
            "date_taken": "2009-12-07T21:28:16-08:00",
            "description": "<p><a href=/"http://www.flickr.com/people/pamelasag61//">pamelasag61<//a> posted a photo:<//p> <p><a

href=/"http://www.flickr.com/photos/pamelasag61/4306947712//" title=/"Parade car __D_09-12-07/"><img

src=/"http://farm5.static.flickr.com/4011/4306947712_0a94f2fd05_m.jpg/" width=/"240/" height=/"150/" alt=/"Parade car __D_09-12-07/" /><//a><//p> ",
            "published": "2010-01-26T16:12:40Z",
            "author": "[email protected] (pamelasag61)",
            "author_id": "9592695@N03",
            "tags": "man car parade"
       },
       {
            "title": "2011 Ford Mustang GT Official Pace Car of the Daytona 500",
            "link": "http://www.flickr.com/photos/dream-car-tv/4306162859/",
            "media": {"m":"http://farm5.static.flickr.com/4006/4306162859_91446da327_m.jpg"},
            "date_taken": "2010-01-26T16:50:54-08:00",
            "description": "<p><a href=/"http://www.flickr.com/people/dream-car-tv//">www.Dream-car.tv<//a> posted a photo:<//p> <p><a

href=/"http://www.flickr.com/photos/dream-car-tv/4306162859//" title=/"2011 Ford Mustang GT Official Pace Car of the Daytona 500/"><img

src=/"http://farm5.static.flickr.com/4006/4306162859_91446da327_m.jpg/" width=/"240/" height=/"135/" alt=/"2011 Ford Mustang GT Official Pace Car of the Daytona 500/"

/><//a><//p> ",
            "published": "2010-01-26T15:50:54Z",
            "author": "[email protected] (www.Dream-car.tv)",
            "author_id": "35138136@N04",
            "tags": "ford car official pace mustang 500 gt daytona 2011"
       }
        ]
})



什麼是JASONP格式?


$.AJAX()方法
$.ajax(options) 改方法只有一個參數,但在這個對象裏包含了$.ajax()所需要的請求設置以及回調函數,參數以Key/value的形式存在,所有的參數都是可選的。常用參數如下:

url String 發送請求的地址

type string 請求方式 默認爲GET,注意其他HTTP請求方法,例如PUT和DELETE也可以使用,單僅部分瀏覽器支持

timeout Number 設置請求超時時間(毫秒)。此設置將覆蓋$.ajaxSetup()方法的全局設置

data Object或String 發送到服務器的數據。將自動轉換爲字符串格式。。防止這種自動轉換,可以查看processData選項,對象必須爲KEY/VALUE格式。
例如{foo1:"bar1",foo2:"bar2"}轉換爲&foo1=bar1&foo2=bar2
如果是數組,jquery將自動爲不同值對應同一個名稱
{foo:["bar1",bar2]}轉換爲&foo=bar1&foo=bar2

datatype String  預期服務器返回的數據類型。
如果不指定,jquery將自動根據http包MIME信息返回responseXML或responseText ,並作爲回調參數傳遞。

可用的類型如下:
xml:返回XML文檔,可用jquery處理

html:返回純文本HTML信息,包含的script標籤會在插入DOM時執行

script:返回純文本JavaScript代碼。不會自動緩存結果。除非設置了cache參數。注意才遠程請求時(不在同一個域下),所有POST請求都將轉爲GET請求

域的概念是什麼?


jason:返回JASON數據

jasonp:使用SONP形式調用函數時,例如myurl?callback=?,JQUERY將自動替換後一個"?"爲正確的函數名,以執行回調函數

text:返回純文本字符串


beforeSend Function  發送請求前可用修改XMLHttpRequest對象的函數,例如添加自定義HTTP頭。在beforeSend中,如果返回false,可用取消本次請求。
                     XMLHttpRequest對象是唯一的參數。 function(XMLHttpRequest){this;}

complete  Function 請求完成後調用的回調函數(請求成功或失敗後均調用) function(XMLHttpRequest,textStatus){this;}

success Function 請求成功後調用的回調函數,由服務器返回,並根據datatype參數進行處理後的數據 function (data,textStatus){};

error Function    請求失敗時被調用的函數  function(XMLHttpRequest ,textStatus,errorThrown){} //通常情況下textStatus,errorThrown只有其中一個包含信息

global Boolean 默認爲true.表示是否觸發全局ajax事件.設置爲false,將不會觸發全部ajax事件,AjaxStart或AjaxStop可用於控制各種Ajax事件

AjaxStart或AjaxStop是什麼?




序列化元素

1.serialize()方法
如果表單元素複雜,使用ajax對數據的操作也太大,缺乏彈性。所以提供了這個方法。
該方法能夠將DOM元素序列化爲字符串,用於AJAX請求。

不光表單可以使用此方法,其他選擇器選取的元素也都能使用它。

上面的例子改進成:
    $(function(){
       $("#send").click(function(){
            $.get("get1.php", $("#form1").serialize() , function (data, textStatus){//.serialize()也會自動將編碼問題解決,實現自動轉碼
                        $("#resText").html(data); // 把返回的數據添加到頁面上
                    }
            );
       })
    })

var $data = $(":checkbox,:radio").serialize();
返回的是check=1&check=2&check=3&check=4&radio=3,僅僅對值的序列化爲字符串形式


    $(function(){
       $("#send").click(function(){
            $.get("get1.php", "username="+encodeURIComponent($('#username').val())+"&content="+encodeURIComponent($('#content').val()), function (data,

textStatus){
                        $("#resText").html(data); // 把返回的數據添加到頁面上
                    }
            );
       })
    })


encodeURIComponent和escape() encodeURI()的區別是什麼?
unescape  不會被此方法編碼的字符: @ * / +
encodeURI() 方法:把URI字符串採用UTF-8編碼格式轉化成escape格式的字符串。不會被此方法編碼的字符:! @ # $& * ( ) = : / ; ? + '不會被此方法編碼的字符:! * ( )
encodeURIComponent      不會被此方法編碼的字符:! * ( )

因此,對於中文字符串來說,如果不希望把字符串編碼格式轉化成UTF-8格式的(比如原頁面和目標頁面的charset是一致的時候),只需要使用 escape。如果你的頁面是GB2312或者其他的

編碼,而接受參數的頁面是UTF-8編碼的,就要採用encodeURI或者 encodeURIComponent。

另外,encodeURI/encodeURIComponent是在javascript1.5之後引進的,escape則在javascript1.0版本就有。


2.serializeArray()
 該方法不是返回字符串,而是將DOM元素序列化後,返回JSON格式的數據。
   $(function(){
         var fields = $(":checkbox,:radio").serializeArray();
         console.log(fields);// Firebug輸出
         $.each( fields, function(i, field){
            $("#results").append(field.value + " , ");
        });
   })


3.param()方法
它是serialize()方法的核心,用來對一個數組或對象按照key/value進行序列化。

    $(function(){
          var obj={a:1,b:2,c:3};
        var  k  = $.param(obj);
        alert(k)        // 輸出  a=1&b=2&c=3
    })

返回的數據爲:
a=1&b=2&c=3


JQuery中的Ajax全局事件
只要是調用JQUERY觸發的Ajax的請求,就會觸發公用的全局事件

Ajax請求開始時,會觸發ajaxStart()
Ajax請求結束時,會觸發ajaxStop()

ajaxComplete(callback) Ajax請求完成時執行的函數
ajaxEroor(callback)Ajax請求發生錯誤時執行的函數,捕捉到的錯誤可以最爲最後一個參數傳遞
ajaxSend(callback)Ajax請求發送前執行的函數
ajaxSuccess(callback)Ajax請求成功時執行的函數

例子:
#loading{
    width:80px;
    height: 20px;
    background:#bbb;
    color:#000;
    display:none;
}

<div id="loading">加載中...</div>


//共用這2個全局的ajax事件
       $("#loading").ajaxStart(function(){
          $(this).show();
       });
       $("#loading").ajaxStop(function(){
          $(this).hide();
       });


例子2:
$("status",xml)方法 通知jQuery去XML文檔中尋找"status"標籤。
$("status",xml).text() 尋找"status"標籤的值


<style type="text/css">
        body{
           margin:0;
           padding:0;
           font-size:12px;
        }
        #messagewindow {
            height: 250px;
            border: 1px solid;
            padding: 5px;
            overflow: auto;
        }
        #wrapper {
            margin: auto;
            width: 438px;
        }
    </style>


<div id="wrapper">
        <p id="messagewindow"><span id="loading">加載中...</span></p>
        <form id="chatform" action="#">
            姓名: <input type="text" id="author" size="50"/><br />
            內容: <input type="text" id="msg"  size="50"/>   <br />
            <input type="submit" value="發送" /><br />
        </form>
    </div>

    $(function(){
            //定義時間戳
            timestamp = 0;
            //調用更新信息函數
            updateMsg();
            //表單提交
            $("#chatform").submit(function(){
                $.post("backend.php",{
                            message: $("#msg").val(),
                            name: $("#author").val(),
                            action: "postmsg",
                            time: timestamp
                        }, function(xml) {
                    //清空信息文本框內容
                    $("#msg").val("");
                    //調用解析xml的函數
                    addMessages(xml);
                });
                return false; //阻止表單提交
            });
        });
        //更新信息函數,每隔一定時間去服務端讀取數據
        function updateMsg(){
            $.post("backend.php",{ time: timestamp }, function(xml) {
                //移除掉 等待提示
                $("#loading").remove();
                //調用解析xml的函數
                addMessages(xml);
            });
             //每隔4秒,讀取一次.
            setTimeout('updateMsg()', 4000);
        }
        //解析xml文檔函數,把數據顯示到頁面上
        function addMessages(xml) {
            //如果狀態爲2,則終止
            if($("status",xml).text() == "2") return;
            //更新時間戳
            timestamp = $("time",xml).text();
            //$.each循環數據
            $("message",xml).each(function() {
                var author = $("author",this).text(); //發佈者
                var content = $("text",this).text();  //內容
                var htmlcode = "<strong>"+author+"</strong>: "+content+"<br />";
                $("#messagewindow").prepend( htmlcode ); //添加到文檔中
            });
        }



php的內容
 <?php
// 配置信息:
// 1,數據庫連接的具體信息
// 2,我們要存儲的消息的數目
// 3,用戶進到聊天室的時候消息顯示的數目
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "123456";
$dbname = "chat";
$store_num = 10;
$display_num = 10;

// 錯誤報告
error_reporting(E_ALL);

// 頭部信息
header("Content-type: text/xml;charset=gb2312");
header("Cache-Control: no-cache");


//連接mysql
$dbconn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname,$dbconn);

//爲容易操作請求數據,我們爲請求中的每個參數設置一個變量,每個變量將把請求中的參數值作爲其自己的值
//foreach語句遍歷所有的POST數據,並且爲每個參數創建一個變量,並且給它賦值
foreach($_POST as $key => $value){
    $$key = mysql_real_escape_string($value, $dbconn);
}
 
//屏敝任何錯誤提示,判斷action是否等於 postmsg
if(@$action == "postmsg"){
    //插入數據
 
    mysql_query("INSERT INTO messages (`user`,`msg`,`time`)
                 VALUES ('$name','$message',".time().")",$dbconn);
    //刪除數據(因爲我們默認值存儲10條數據)
    mysql_query("DELETE FROM messages WHERE id <= ".
                (mysql_insert_id($dbconn)-$store_num),$dbconn);
}

//查詢數據
$messages = mysql_query("SELECT user,msg
                         FROM messages
                         WHERE time>$time
                         ORDER BY id ASC
                         LIMIT $display_num",$dbconn);
//是否有新記錄
if(mysql_num_rows($messages) == 0) $status_code = 2;
else $status_code = 1;

//返回xml數據結構
echo "<?xml version=/"1.0/"?>/n";
echo "<response>/n";
echo "/t<status>$status_code</status>/n";
echo "/t<time>".time()."</time>/n";
if($status_code == 1){ //如果有記錄
    while($message = mysql_fetch_array($messages)){
        $message['msg'] = htmlspecialchars(stripslashes($message['msg']));
        echo "/t<message>/n";
        echo "/t/t<author>$message[user]</author>/n";
        echo "/t/t<text>$message[msg]</text>/n";
        echo "/t</message>/n";
    }
}
echo "</response>";
?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章