我有一个foo发出Ajax请求的函数.我怎样才能从中回复foo?
我尝试从success回调中返回值,并将响应分配给函数内部的局部变量并返回该变量,但这些方法都没有实际返回响应.
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result;
}
var result = foo(); // It always ends up being `undefined`.
Run Code Online (Sandbox Code Playgroud) 鉴于以下示例,为什么outerScopeVar在所有情况下都未定义?
var outerScopeVar;
var img = document.createElement('img');
img.onload = function() {
outerScopeVar = this.width;
};
img.src = 'lolcat.png';
alert(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)
var outerScopeVar;
setTimeout(function() {
outerScopeVar = 'Hello Asynchronous World!';
}, 0);
alert(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)
// Example using some jQuery
var outerScopeVar;
$.post('loldog', function(response) {
outerScopeVar = response;
});
alert(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)
// Node.js example
var outerScopeVar;
fs.readFile('./catdog.html', function(err, data) {
outerScopeVar = data;
});
console.log(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)
// with promises
var outerScopeVar;
myPromise.then(function (response) {
outerScopeVar = response;
});
console.log(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)
// geolocation API
var outerScopeVar; …Run Code Online (Sandbox Code Playgroud) 我正在努力使用 javascript 模块......
我有一个 html 文件和一个 JS 模块。我在 javascript 文件中定义了一个函数,我想从 HTML 页面调用该函数。这是我的代码
索引.html
<html>
<head>
<script type="module" src="app.js"></script>
</head>
<body>
<button onclick="greetFromHtml();">greetFromHtml</button>
<button onclick="greetFromModule()"> greetFromModule</button>
<script type="text/javascript">
function greetFromHtml(){
alert('Hello');
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
应用程序.js
function greet(){
alert('Hello');
}
Run Code Online (Sandbox Code Playgroud)
greetFromHtml 按钮工作正常。当我单击greetFromModule按钮时,出现以下错误:hello is not defined at HTMLButtonElement.onclick
如果我type="module"从标头中删除,一切正常,但是由于其他原因我需要使用模块,所以这不是一个好的解决方案。
我看过几篇文章说我需要导入/导出或使用窗口,但我不知道该怎么做。请问有人可以提供答案吗?理想情况下,实现它的最简单方法
请参阅下面对我审查过的一些问题的参考:
编辑2 答案中的代码正在运行。我只是尝试在本地运行,但我知道您需要一台服务器,因此如果您看到相同的错误,请将站点上传到服务器或使用本地服务器。