作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在函数外部alert(httpAccept)
,但这是不可能的。所有操作都必须在 httpAcceptResponse(data)
内进行。
当我在 getHTTP() 之后 consol httpAccess 时,我得到
资源解释为脚本,但使用 MIME 类型 text/html 传输:“http://www.domain.com/httpaccept.php?callback=httpAcceptResponse ”。
解决这个问题的方法是什么?
function requestServerCall(url) {
var head = document.head;
var script = document.createElement("script");
script.setAttribute("src", url);
head.appendChild(script);
head.removeChild(script);
}
var httpAccept = '';
function httpAcceptResponse(data) {
httpAccept = data.token;
}
function getHTTP() {
requestServerCall("http://www.domain.com/httpaccept.php?callback=httpAcceptResponse");
}
getHTTP();
最佳答案
您需要绑定(bind)回调。像这样的东西:
var httpAcceptResponse;
function getHTTP(callback) {
httpAcceptResponse = callback;
requestServerCall("http://www.domain.com/httpaccept.php?callback=httpAcceptResponse");
}
getHTTP(function(data) {
console.log(data.token);
// now you have the variable
});
编辑:如果要全局使用,请在回调中设置:
getHTTP(function(data) {
window.httpAccept = data.token;
});
但是请注意,在调用回调之前,该变量在全局范围内不可用。
关于javascript - 如何在 JavaScript 中打印函数外部的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25412275/
我是一名优秀的程序员,十分优秀!