我正在学习制作Chrome扩展程序。我正在构建一个字典,它从弹出窗口的输入字段中获取一个单词。然后,此弹出窗口返回单词的定义。
问题:当我调用函数apicall()
时,request.onload
在函数返回后执行得很多。这使得definition
变量在显示时保持为空。有关说明,请查看控制台日志下方。
我尝试过添加等待功能但没有帮助。它的搜索时间过长,我真的没有想法。非常感谢任何帮助!
extension.js
var word = "", definition = "";
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('status').textContent = "Extension loaded";
var searchButton = document.getElementById('searchButton');
searchButton.addEventListener('click', function() {
word = $('#textInput').val();
if(!word){
$('#status').html("Please enter a word");
return;
}
apicall();
console.log("**returned from apicall**" + definition);
$('#status').html(definition);
})
addButton.addEventListener('click', function() {
$('#status').html('The word is added to the list');
})
})
的script.js
function apicall(){
var url = 'http://api.pearson.com/v2/dictionaries/entries?headword=' + word;
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.setRequestHeader('accept', "application/json");
console.log("**apicall:outside**\n");
request.onload = function() {
//Begin accessing JSON data here
console.log("**apicall:inside**\n");
var data = JSON.parse(this.response);
definition = data.results[0].senses[0].definition;
// if(definition.length != 0)
// definition = definition.charAt(0).toUpperCase() + definition.slice(1);
console.log('definition='+definition);
}
request.send();
}
控制台
**apicall:outside** scripts1.js:16
**returned from apicall** extension.js:16
**apicall:inside** scripts1.js:21
definition=hello scripts1.js:28