jquery插件从ajax获取选项
我正在创建一个jquery插件。我想从后端获取数据,并作为选项发送到插件jquery插件从ajax获取选项,jquery,ajax,Jquery,Ajax,我正在创建一个jquery插件。我想从后端获取数据,并作为选项发送到插件 function getData(){ $.when(http_get('../list/')).then(function(response){ students = response; return students; console.log(response); }, function(response){ console.log
function getData(){
$.when(http_get('../list/')).then(function(response){
students = response;
return students;
console.log(response);
}, function(response){
console.log('get failed');
})
}
$('#element').pluginSmart({
data: getData()
});
这里我从后端获取数据,但它没有分配给插件的数据选项
function getData(){
$.when(http_get('../list/')).then(function(response){
students = response;
return students;
console.log(response);
}, function(response){
console.log('get failed');
})
}
$('#element').pluginSmart({
data: getData()
});
我知道数据是在ajax返回之前分配的。如何等待ajax返回,然后分配
我想保持它插件初始化简单。否则,我会在then函数中启动插件。您必须在初始化插件之前检索数据。将初始化代码放入AJAX请求的回调中,例如:
$.get('../list/', function(response){
students = response;
console.log(response);
$('#element').pluginSmart({
data: students;
});
}).fail({
console.log('get failed');
});
或者,您可以执行同步请求,但这是一种可怕的做法(请参阅:)我找到了一种更好的方法来处理这种情况。因为我的目标是保持插件初始化简单。我只是将url传递到插件中,然后从插件内部获取数据 ajax是异步的,不管怎样,你的getData()方法都不会返回任何东西。我可以用其他方式将远程数据设置为插件选项吗?从插件中调用ajax,就像我说的,这个插件应该尽可能简单地初始化。所以我不能在另一个ajax调用中使用它,“简单”是一个主观的衡量标准。我不认为这种方法有任何复杂之处。无论如何,我很高兴你解决了你的问题。我想以插件的形式发布我的作品。所以我想确保非程序员可以轻松地使用它。
function getData(){
$.when(http_get('../list/')).then(function(response){
students = response;
return students;
console.log(response);
}, function(response){
console.log('get failed');
})
}
$('#element').pluginSmart({
data: getData()
});