首页 > 解决方案 > 你如何在ajax中创建一个变量,对函数的其余部分是全局的

问题描述

我正在尝试通过 jquery 中的数据库获取一些数据。我通过 ajax 执行此操作,ajax 代码返回值很好。然后我用数据设置一个变量comment

然后使用注释变量将 html 插入到元素中。但是,这个变量似乎没有设置,因为它没有通过 ajax 函数传递。我该如何做到这一点?

$(document).on('click', '.customer_progress_edit', function(){
   timeline_id = $(this).attr('data-timeline');
    $.ajax({ 
       type : 'POST',
       url      : '//'+base_url+'/ajax2/timeline-comment.php',
       data : 'timeline_id='+timeline_id,
       success  : function(data) {
           comment = data;
       }
   });
   $('#customer_pop_edit_comment').val(comment);
}); 

是的,我知道我可以简单地在 ajax 函数中使用 html() 函数,但我已经简化了代码,以便更容易地了解我想要实现的目标,它不仅仅是这个。

标签: jqueryajaxvariablesglobal-variables

解决方案


try this

var get_data = $.ajax({
type : 'POST',
url  : '//'+base_url+'/ajax2/timeline-comment.php',
data : 'timeline_id='+timeline_id
});
get_data.done(function(html){
    comment = html;
});

推荐阅读