繁体   English   中英

Javascript:我如何为 2 个不同的 html 页面使用“全局变量”?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM