2011-12-22 33 views
1

我有下面的代碼從AJAX請求中獲取一些html,然後隱藏表中的一行並顯示另一個,但即使我創建的var用於存放html(quick_edit_html )在AJAX函數運行後(通過將其放入警告框中進行測試)可用時,Firebug告訴我,當我嘗試在下一個函數中使用它時,它不存在(在AJAX請求完成之前它不會運行) 。AJAX/jQuery-var不存在

關於我要去哪裏的任何想法都是錯誤的?

/** Run the AJAX request to grab the qucik edit html */ 
var load_quick_edit = jQuery.post(MyAjax.ajaxurl, data, function(response){ 
    var quick_edit_html = response; 
}); 

/** Display the correct quick edit row */ 
load_quick_edit.done(function(){ 

    /** Hide the row that is to be edited */ 
    jQuery('tr#display-'+slug).hide(); 

    /** Show the quick edit row that the user has requested */ 
    jQuery('tr#quick-edit-'+slug).show(); 
    jQuery('tr#quick-edit-'+slug).html(quick_edit_html); 

}); 

謝謝。

回答

2

您的var是在匿名ajax回調函數中聲明的。這個範圍將var指向該函數,這意味着無法從其他任何地方訪問該函數。

只需在函數外聲明var即可。

var quick_edit_html; 

/** Run the AJAX request to grab the qucik edit html */ 
var load_quick_edit = jQuery.post(MyAjax.ajaxurl, data, function(response){ 
    quick_edit_html = response; 
}); 

/** Display the correct quick edit row */ 
load_quick_edit.done(function(){ 

    /** Hide the row that is to be edited */ 
    jQuery('tr#display-'+slug).hide(); 

    /** Show the quick edit row that the user has requested */ 
    jQuery('tr#quick-edit-'+slug).show(); 
    jQuery('tr#quick-edit-'+slug).html(quick_edit_html); 

}); 
+0

謝謝 - 以爲它會有點愚蠢! – 2011-12-22 15:18:01

1

quick_edit_html應在該時間點已經超出範圍。您可以嘗試也許是它在全球範圍內或原型範圍存儲(與該關鍵字)

+0

我希望看到使用'this'關鍵字的實現。我總是依賴全局或命名空間範圍,但替代方法很好。 – 2011-12-22 15:15:47

+0

謝謝,它對它進行了排序。 – 2011-12-22 15:18:47

2

這是不可用,因爲它的出範圍。聲明它在post()之外:

var quick_edit_html; 

    /** Run the AJAX request to grab the qucik edit html */ 
var load_quick_edit = jQuery.post(MyAjax.ajaxurl, data, function(response){ 
    quick_edit_html = response; 
}); 

    /** Display the correct quick edit row */ 
load_quick_edit.done(function(){ 
    /** Hide the row that is to be edited */ 
    jQuery('tr#display-'+slug).hide(); 

    /** Show the quick edit row that the user has requested */ 
    jQuery('tr#quick-edit-'+slug).show(); 
    jQuery('tr#quick-edit-'+slug).html(quick_edit_html); 
}); 
+0

謝謝,這就是訣竅。 – 2011-12-22 15:18:30