簡體   English   中英

如何在JavaScript中的函數外部打印變量?

[英]How to print the variable outside of the function in JavaScript?

我想在函數外部發出alert(httpAccept) ,但這是不可能的。 我必須在httpAcceptResponse(data)內部進行所有操作。

當我在getHTTP()之后合並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();

您需要綁定回調。 就像是:

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;
});

但是請注意,在調用回調之前,變量在全局范圍內不可用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM