如何在同一函数中访问“mentorslist”变量。 “mentorslist”是ajax调用的成功。但我无法在 Mentors() 函数中访问它。
function mentors(){
var mentorslist = '';
$.ajax({
type: "POST",
url: <?php echo '"'.base_url().'index.php/MentorList/'.'"'; ?>,
data: { pagelimit: 1,json: "true" },
success: function( msg )
{
var obj = jQuery.parseJSON(msg);
var $mentor_list ="";
var mlist = '';
jQuery.each( obj.resset, function( i, val ){
mlist = mlist+'<option value="'+val.mentor_Id+'">'+val.Name+'</option>';
$("#mlist").get(0).options[$("#mlist").get(0).options.length] = new Option(val.Name,val.mentor_Id);
});
mentorslist = mlist; //Able to access here
}
});
return mentorslist; // gives undefine error
}
看到这里,mentorslist 变量正在设置为 ajax success 并尝试通过自定义函数返回该变量,但它返回给我未定义。
最佳答案
因为 Ajax 是异步的,所以只有当成功事件被触发时,您才拥有变量值。因此,您可以定义自己的函数来调用成功:
var mentorslist = '';
function mentors(myCallBack) {
return $.ajax({
type: "POST",
url: "yourPHP",
data: {pagelimit: 1, json: "true"},
success: function(msg) {
myCallBack(msg);
}
});
}
mentors(function(msg) {
var obj = jQuery.parseJSON(msg);
var $mentor_list = "";
var mlist = '';
jQuery.each(obj.resset, function (i, val) {
mlist = mlist + '<option value="' + val.mentor_Id + '">' + val.Name + '</option>';
$("#mlist").get(0).options[$("#mlist").get(0).options.length] = new Option(val.Name, val.mentor_Id);
});
mentorslist = mlist; //Able to access here
});
在任何情况下,您都可以始终将 ajax 调用的 async 属性设置为 false,以便将 ajax 调用从异步更改为同步:
function mentors(){
var mentorslist = '';
$.ajax({
async: false,
type: "POST",
url: <?php echo '"'.base_url().'index.php/MentorList/'.'"'; ?>,
data: { pagelimit: 1,json: "true" },
success: function( msg )
{
var obj = jQuery.parseJSON(msg);
var $mentor_list ="";
var mlist = '';
jQuery.each( obj.resset, function( i, val ){
mlist = mlist+'<option value="'+val.mentor_Id+'">'+val.Name+'</option>';
$("#mlist").get(0).options[$("#mlist").get(0).options.length] = new Option(val.Name,val.mentor_Id);
});
mentorslist = mlist; //Able to access here
}
});
return mentorslist;
}
关于javascript - Ajax成功函数无法在自定义函数内访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36114908/