DIV CSS 佈局教程網

Ajax 回呼函式裡 $(this) 取不到物件,怎麼辦
編輯:AJAX基礎知識     

寫 jQuery 時有個很常踩的坑:在 $.ajax 的 success 回呼裡使用 $(this),結果什麼都取不到。原因不難理解,但如果不特別注意,很容易卡上半天。

問題的根源:this 已經換人了

當你把回呼函式傳給 $.ajax 時,那個函式是在請求完成後由 jQuery 內部呼叫的。此時 this 指向的是 jQuery 的設定物件(options),而不是你原本所在的 DOM 元素或外層函式。所以 $(this) 抓不到任何你想操作的節點。

jQuery 提供了 context 參數可以改寫這件事,但更通用、也更直觀的做法是:在進入 Ajax 之前,先把需要的 jQuery 物件存成變數。

可用的寫法

$(".derek").each(function () {
    $(this).click(function () {
        var params = $(this).parent().serialize();
        var obj  = $(this).parent().siblings("div#caskContent");
        var form = $(this).parent();

        $.ajax({
            url: "editCaskContent",
            type: "post",
            data: params,
            dataType: "json",
            success: function (e) {
                obj.empty();
                obj.html("<font color=\"#00AA00\">追問:</font>");
                obj.append(e.caskContent);
                form.toggle();
                alert("修改成功!");
            },
            error: function (e) {
                alert(e);
            }
        });
    });
});

注意 obj 與 form 這兩個變數:它們在發出請求之前就已經定義好,透過閉包被回呼函式捕獲。無論回呼裡的 this 指向誰,obj 與 form 永遠指向正確的元素。這是+function 作用域的必然結果,也是處理這類問題最乾淨的方式。

另一種做法:用 context 參數

$(".derek").each(function () {
    $(this).click(function () {
        var self = this;   // 有時候你需要的是原生元素
        $.ajax({
            url: "editCaskContent",
            type: "post",
            data: $(this).parent().serialize(),
            dataType: "json",
            context: this,          // 讓回呼裡的 this 指向這個元素
            success: function (e) {
                $(this).siblings("div#caskContent").html(e.caskContent);
            }
        });
    });
});

兩種做法都可行。 personally 我更偏好前者——把要用的元素提前存成變數,程式碼讀起來一目了然,不必回頭去查 context 設了什麼。而且當回呼裡需要同時用到多個元素時,context 只能指定一個,變數法則沒有這個限制。

順帶一提

範例裡用了 <font color="#00AA00"> 這種老寫法,現在一律建議改用 CSS class 控制顏色,樣式與結構分離才好維護。

另外 error 回呼直接 alert(e) 會把整個物件的字串表示丟給使用者看,實際上毫無意義。比較合適的做法是記到 console,並對使用者顯示友善的錯誤提示。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved