我正在使用 2 個不同的 html,并且都使用相同的 Javascript 檔案。
Javascript 檔案執行此操作
var problem;
function login() {
const login = document.getElementById('login');
const nome = document.getElementById('lnome');
const pass = document.getElementById('lpass');
const item = {
Username: nome.value.trim(),
Password: pass.value.trim()
};
fetch(uri, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(item)
})
.then(response => response.json())
.then((res) => {
problem = res; //HERE need to put into the 'problem' the value of the res
window.location.href = url_1; // This calls index_2.html
})
.catch(error => console.error('Unable to Login.', error));
}
上面的代碼在 index_1.html 中使用
$(function () {
var $users_A = $('#users_A');
$.ajax({
url: uri_1,
type: 'GET',
dataType: 'json',
beforeSend: function (request) {
request.setRequestHeader("Authorization", 'Bearer ' problem);
},
success: function (data) {
$users_A.append('<h4>PROBLEM RESOLVED</h4>');
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
$users_A.append('<h4>DON'T WORK</h4>');
}
});
});
上面的代碼在 index_2.html 中使用
當我運行程式時,變數問題不包含“res”中的資訊,所以它變得未定義,我如何解決這個問題?
歡迎任何答案
uj5u.com熱心網友回復:
全域變數僅對當前加載的使用它的頁面是全域的。它不是對所有可能重用相同代碼的頁面都是全域的。如果您需要資料可用于單個用戶的所有頁面,請將資料存盤在localStorage. 如果您需要在所有頁面上的所有用戶之間共享資料,則需要將資料存盤在服務器上。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/475757.html
標籤:javascript html 变量
上一篇:以編程方式生成Gatsby頁面,無需Graphql的slug
下一篇:我怎樣才能讓機器人回復dms
