我尝试将我的数组传递给外部函数失败了吗?以下是jsbin中的工作代码:https://jsbin.com/kugesozawi/edit?js,console,output结果应该传递给returnSearch。
var googleSuggest = function(returnSearch){
var term = $('#searchInput').val();
var result = [];
var service = {
youtube: { client: 'youtube', ds: 'yt' },
books: { client: 'books', ds: 'bo' },
products: { client: 'products-cc', ds: 'sh' },
news: { client: 'news-cc', ds: 'n' },
images: { client: 'img', ds: 'i' },
web: { client: 'hp', ds: '' },
recipes: { client: 'hp', ds: 'r' }
};
$.ajax({
url: 'https://clients1.google.com/complete/search',
dataType: 'jsonp',
data: {
q: term,
nolabels: 't',
client: service.web.client,
ds: service.web.ds
}
}).done(function(data) {
result.pop()
$.each(data[1], function(item, value) {
var stripedValue = value[0].replace(/<[^>]+>/g, '');
result.push(stripedValue);
})
console.log(result)
})
returnSearch = ['ActionScript', 'AppleScript', 'Asp']
return returnSearch
};
答案 0 :(得分:-1)
我认为让它返回你想要的值的唯一方法是使调用同步,这意味着无论何时调用ajax调用,你都必须等待它准备就绪(你通常会这样做)不想要)。您可以在结果调用中调用returnSearch
函数,如下所示:
var googleSuggest = function(returnSearch){
var term = $('#searchInput').val();
var service = {
youtube: { client: 'youtube', ds: 'yt' },
books: { client: 'books', ds: 'bo' },
products: { client: 'products-cc', ds: 'sh' },
news: { client: 'news-cc', ds: 'n' },
images: { client: 'img', ds: 'i' },
web: { client: 'hp', ds: '' },
recipes: { client: 'hp', ds: 'r' }
};
var promise = $.ajax({
url: 'https://clients1.google.com/complete/search',
dataType: 'jsonp',
data: {
q: term,
nolabels: 't',
client: service.web.client,
ds: service.web.ds
}
})
return promise
};
$(function() {
$('#searchInput').autoComplete({
minChars: 1,
source: function(term, suggest){
var promise = googleSuggest()
returnSearch = function(term, choices) {
console.log(choices)
var suggestions = [];
for (i=0;i<choices.length;i++)
if (~choices[i].toLowerCase().indexOf(term)) suggestions.push(choices[i]);
suggest(suggestions);
}
$.when(promise).then(function(data) {
term = term.toLowerCase();
var result = [];
$.each(data[1], function(item, value) {
var stripedValue = value[0].replace(/<[^>]+>/g, '');
result.push(stripedValue);
})
returnSearch(term, result)
})
}
});
})