jQuery 中使用 ajax 進行資料交換

先前我們有提到 jQuery 能利用 json 進行資料交換,這篇則是要透過 ajax 進行資料交換,我們使用 get 和 post 的方式,透過 ajax 的技術能對 php、jsp、asp等等不同的伺服器端語言進行資料交換,說明如下:

一、.get()

syntax:jQuery.get( url [, data ] [, success ] [, dataType ] )

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $.get("http://www.w3schools.com/jquery/demo_test.asp", function (data, status) {
                    $("#myText").text("Data: " + data + " Status: " + status);
                },"html");
            });
        });
    </script>
</head>
<body>

    <p id="myText">a Text</p>
    <button>Send an HTTP GET request to a page and get the result back</button>

</body>
</html>

JS Bin

demo_test.asp檔案內容為

This is some text from an external ASP file.

1.先來看sucess function function (data, status,dataType){}

(1).當使用.get()方法去server端get資料成功後,會把相關資訊放在第一参數(data)與第二參數(status)。

(2).其中的function(data,status,dataType){...},data與status、dataType参數的變數命名式可以隨意取的。

(3).最主要是變數的順序不能動,第一参數為server端回傳的內容,第二參數為http狀態,第三個參數為回傳資料預定格式。

(4).這三個參數都是optional的。

(5)第三個參數可指定為json、xml、html等。

2.此程式的動作為當按下按鈕時,a Text文字會被替換成This is some text from an external ASP file.

當你在測試的時候卻發現無法動作,如果你有按F12打開console查看錯誤訊息時,就會發現

「XMLHttpRequest cannot load http://www.w3schools.com/jquery/demo_test.asp.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://null.jsbin.com' is therefore not allowed access.」

這段錯誤訊息,主要原因為當傳輸方式使用get或post時,伺服端並沒有允許你擁有跨網站存取權限,

所以按下按鈕去get資料回來卻是失敗的。

測試網址如下:

http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_get

3.另外jQuery還有$("selector").get();語法,

這是用來取得該element的object,是個完全不同的東西。

二、post技術

$.post()

syntax:$.post(URL,data,callback);

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $.post("demo_test_post.asp",
                {
                    name: "Donald Duck",
                    city: "Duckburg"
                },
                function (data, status) {
                    $("#myText").text("Data: " + data + " Status: " + status);
                });
            });
        });
    </script>
</head>
<body>

    <p id="myText">a Text</p>
    <button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>

此程式的功能為按下按鈕時,將name與city所設定的值post到server端並取得所吐回的資料再秀出來。

測試網址如下:

http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_post

$.post()相當等於$.ajax(),用法大致相同唯有ajax的type要指定為post,範例如下

$.ajax({
    type: "POST",
    url: url,
    data: data,
    success: success,
    dataType: dataType
});

2.MVC範例-使用post技術

三、jqXHR

jqXHR有提供jqXHR.done()、jqXHR.fail()、jqXHR.always()方法讓USER來使用

另外jqXHR.success()、jqXHR().error()、jqXHR.complete()於jQuery 1.8不推薦使用

程式範例:

var jqxhr = $.get("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");
});

四、jQuery.ajax()

請先參考jQuery.ajax()

留言

這個網誌中的熱門文章

c語言-關於#define用法

PHP教學 - 資料型態(Data Type) - 上

CMD常用網管指令