8.05.2014

jQuery AJAX HTTP POST Request (GoAhead)

AJAX這個技術從JavaScript學習到jQuery,自己摸著良心講,只懂了一點點─最啟碼已經知道它是如何運作的、也知道如何利用一些工具例如像Mozilla FireFox的瀏灠器主控台,或是WireShark來追蹤HTTP GET and POST Request Response的行為模式。

jQuery這個JavaScript的Framework對於AJAX的支援非常地多。$.ajax()只是其中最通用的一項。當然還有許多其它的函式,這個網頁:jQuery 参考手冊 - Ajax,都有詳盡的介紹。

這一次,一樣是用jQuery來實現AJAX的技術,但不再用$.ajax()函式,而改用其它函式來搭配組合;後端的Web Server改成另一套Embedded Linux的GoAhead

在程式碼的主體上,就不再重寫,直接把差異的部份給呈現出來。

首先,我在<body>主體前面,增加一個JavaScript函式,它能夠呈現當時的時間,格式如下:20140804 (MON) 15:09:36
var objCurrentTime = function() {
    var Ret = new Date();
    var obj = {
        year: Ret.getFullYear(),
        month: function() {
            var tmp = Ret.getMonth() + 1;
            return (tmp < 10)? ("0" + tmp): tmp;
        },
        date: function() {
            var tmp = Ret.getDate();
            return (tmp < 10)? ("0" + tmp): tmp;
        },
        hour: function() {
            var tmp = Ret.getHours();
            return (tmp < 10)? ("0" + tmp): tmp;
        },
        minute: function() {
            var tmp = Ret.getMinutes();
            return (tmp < 10)? ("0" + tmp): tmp;
        },
        sec: function() {
            var tmp = Ret.getSeconds();
            return (tmp < 10)? ("0" + tmp): tmp;
        },
        day: function() {
            var tmp = Ret.getDay();
            var week = "";

            switch (tmp) {
                case 0: week = "SUN"; break;
                case 1: week = "MON"; break;
                case 2: week = "TUE"; break;
                case 3: week = "WED"; break;
                case 4: week = "THUR"; break;
                case 5: week = "FRI"; break;
                case 6: week = "SAT"; break;
                default: break;
            }
            return week;
        },
        Result: function() {
            return (this.year + this.month() + this.date() + " (" + this.day() + ") " + this.hour() + ":" + this.minute() + ":" + obj.sec());
        }
    }
    return obj.Result();
}
再來,我再加一個Delay Time的Function (但事後證明,這個Function實在是沒啥用....>"<),目的是為了瞭解AJAX各個階段的先後順序:
function Delay()
{
    var i = -1, j = -1, k = -1;

    for (i = 0; i ++; i < 10000)
        for (j = 0; j++; j < 10000)
            for (k = 0; k++; k < 10000)

    return;
}
在網頁的主體部份,從原本的 <div id="ajax-ServerBack"></div> 置換成以下程式碼,其餘不變:
<div id="ajax-send"></div>
<div id="ajax-start"></div>
<div id="ajax-complete"></div>
<div id="ajax-stop"></div>
<div id="ajax-success"></div>
<div id="ajax-error"></div>
最後,則是jQuery的程序碼:
$(window.document).ready(function() {
    $("#AjaxTest").click(function() {
        $.ajaxSetup({
            cache: true,
          //context: ,
            timeout: 10000,
            global: true,
            contentType: "application/x-www-form-urlencoded",
            async: true,
            processData: true,
            ifModified: false,
          //jsonp: ,
          //username: "admin",
          //password: "admin",
            scriptCharset: "utf-8",
            traditional: true
        });

        $.post(g_strUri() + "/goform/formAjaxTesting", $("#jQueryAjax").serialize(),
            function(data, status, xhr) {
                alert(xhr.responseText);
                return;
            }, "text");

        $("#ajax-send").ajaxSend(function(event, xhr, ajaxOptions) {
            $(this).text(objCurrentTime() + "AJAX request SEND. ");
            Delay();
            return;
        });

        $("#ajax-start").ajaxStart(function() {
            $(this).text(objCurrentTime() + "AJAX request START. ");
            Delay();
            return;
        });

        $("#ajax-complete").ajaxComplete(function(event, xhr, ajaxOptions) {
            $(this).text(objCurrentTime() + "AJAX request COMPLETE. ");
            Delay();
            return;
            });

        $("#ajax-stop").ajaxStop(function() {
            $(this).text(objCurrentTime() + "AJAX request STOP. ");
            Delay();
            return;
        });

        $("#ajax-success").ajaxSuccess(function(event, xhr, ajaxOptions) {
          //$(this).text(objCurrentTime() + " " + xhr.responseText);
            $(this).text(objCurrentTime() + "AJAX request SUCCESS. ");
            Delay();
            return;
        });

        $("#ajax-error").ajaxError(function(event, xhr, ajaxOptions, thrownError) {
            $(this).text(objCurrentTime() + " " + xhr.status + ": An error has occured making the request!! \n");
            Delay();
            return;
        });
        return;
    });
    return;
});
在這個範例裡,我把之前用的$.ajax()置換成$.ajaxSetup()$.post()。前者用來設定一些AJAX的預設值;後者則是用HTTP POST方法來傳遞。

除此之外,jQuery在AJAX部份還提供了許多有用的函式;在這個範例中用上了ajaxSend()ajaxStart()ajaxComplete()ajaxStop()ajaxSuccess()ajaxError()。原本的期望值是能夠在相對應的<DIV>區塊中顯示出來,但實際執行的結果則是----時間都是一樣地!!


但這不打緊,我們還是可以從書中得知AJAX的執行順序

1. ajaxStart();
2. ajaxSend();
3. ajaxSuccess() / ajaxError();
4. ajaxComplete();
5. ajaxStop();

最後,再附上GoAhead Web Server端的程式碼:
int
formAjaxTesting(webs_t wp, char_t *path, char_t *query)
{
    int nBytesSent = 0;
    char_t *pStrVal = NULL;

    pStrVal = websGetVar(wp, T("nmUsername"), T(""));
    if (pStrVal != NULL)
        printf("%s (%d): %s \n", __FUNCTION__, __LINE__, pStrVal);

    pStrVal = websGetVar(wp, T("nmPassword"), T(""));
    if (pStrVal != NULL)
        printf("%s (%d): %s \n", __FUNCTION__, __LINE__, pStrVal);

    websResponse(wp, 200, "Hello!! World!! ", NULL);

    return nBytesSent;
}
在Google資料的過程中,也察覺許多不足之處,像是DTDJSONJSONPXMLSOAP等等,都是將來值得花時間研究的方向。

School Teach Yourself

這個對岸做的教學網頁有非常豐富的資源;除此之外,也找到一些不錯的心得部落格,但這些畢竟是別人的文章,也不可能轉PO到這邊。

這篇文章只是個註記自己的學習概要....其餘不足之處,工作上有遇到的話再記下來吧!!

沒有留言:

張貼留言