[英]Javascript: how i use a ''global variable'' for 2 different html pages?
我正在使用 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”中的信息,所以它變得未定義,我如何解決這個問題?
歡迎任何答案
全局變量僅對當前加載的使用它的頁面是全局的。 它不是對所有可能重用相同代碼的頁面都是全局的。 如果您需要數據可用於單個用戶的所有頁面,請將數據存儲在localStorage
中。 如果您需要在所有頁面上的所有用戶之間共享數據,則需要將數據存儲在服務器上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.