gpt4 book ai didi

javascript - 如何在 JavaScript 中打印函数外部的变量?

转载 作者:行者123 更新时间:2023-12-02 17:04:09 24 4
gpt4 key购买 nike

我想在函数外部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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com