如何在同一功能中访问“ mentorlist”变量。“导师列表”是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成功,并尝试通过自定义函数返回该变量,但是它返回的是我未定义的变量。
因为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调用从async更改为syncnus:
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句