AJAX / JQuery - var不存在

时间:2011-12-22 14:54:02

标签: jquery ajax var

我有下面的代码从AJAX请求中获取一些html,然后隐藏一行表并显示另一行,但即使我创建的用于保存html(quick_edit_html)的var可用AJAX函数已运行(通过将其置于警告框中进行测试),Firebug告诉我,当我尝试在下一个函数中使用它时它不存在(在AJAX请求完成之前它没有运行)。

关于我哪里出错的任何想法?

/** 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);

});

感谢。

3 个答案:

答案 0 :(得分: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);

});

答案 1 :(得分: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);
});

答案 2 :(得分:1)

quick_edit_html应该在那个时间点超出范围。您可以尝试将其存储在全局范围或原型范围内(使用this关键字)

相关问题