如何从我在HTML文件中编写的脚本中访问JavaScript文件中的变量?

时间:2021-05-03 02:22:07

So, I'm making a super basic (and also not secure, because I'm just playing around right now) login system that displays different values for premade graphs based on who you are. I'm accessing the data for the graphs from a JSON with an array of objects that contain things like username, password, number of students, number of students that are boys, girls, etc. I want to have an ID variable that is set in my login page when the person logs in with credentials that match one of the objects' username and password in my JSON file. (the ID would be the index of whatever object the credentials matched). When I make the graphs in my HTML file using chart js, I'm opening the JSON file and accessing one of its objects by that ID and accessing its contents that way. I'm struggling to find a way to reference this ID that is in my JavaScript file in my HTML code "scriptlet", if that's what it is called. Also, I DID try to include the JavaScript file in my html file, but I keep getting errors when I try to reference it in the html how I have in my snippet. Here's a sample of my code:

因此,我正在制作一个超级基础(也不安全,因为我现在只是玩游戏)登录系统,根据您的身份显示预制图表的不同值。我正在从JSON访问图表的数据,其中包含一组对象,其中包含用户名,密码,学生人数,男生,女生等学生人数。我想要设置一个ID变量在我的登录页面中,当用户使用与我的JSON文件中的对象的用户名和密码之一匹配的凭据登录时。 (ID将是凭证匹配的任何对象的索引)。当我使用图表js在我的HTML文件中创建图形时,我打开JSON文件并通过该ID访问其中一个对象并以这种方式访问​​其内容。我正在努力找到一种方法来引用我的HTML代码“scriptlet”中的JavaScript文件中的ID,如果这就是它的名称。此外,我DID尝试将JavaScript文件包含在我的html文件中,但是当我尝试在html中引用它时,我仍然遇到错误。这是我的代码示例:

var objectID; //this is the ID I'm talking about in my question

function clickedLoginButton(){
	var script = document.createElement('script');
	script.src = 'jquery-2.1.4.min.js';
	script.type = 'text/javascript';
	document.getElementsByTagName('head')[0].appendChild(script);

	var user = document.getElementById('username'); //inputted username
	var pass = document.getElementById('password'); //inputted password
  
	var passed = false;
	$.getJSON('data.json', function(data){
		console.log("Length: " + data.length)
		i = 0;
		do{
			console.log(data[i].login);
			if(user.value == data[i].login && pass.value == data[i].pass){
				objectID = i;
				window.open("http://localhost/loggedIn.html", "_self",  true);
				console.log("pass");
				return;
			}
			i++;
		}
		while(i != data.length);
		if(passed == false){
			window.open("http://localhost/loginFailed.html", "_self",  true);
			objectID = 999999999;
			console.log("failed");
		}
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script> //This is where I want to use the object ID
  var numPlayed;
  var numLazy;
  $.getJSON('data.json', function(data){
    var chartData = [
      {
        value: data[objectID].numStudents-data[objectID].numStudentsPlayed,
        color: "dimgray",
        highlight: "gray",
        label: "lazy"
      },
      {
        value:  data[objectID].numStudentsPlayed,
        color: "skyblue",
        highlight: "powderblue",
        label: "played"
      }
    ];
    var ctx = document.getElementById("pieCanvas").getContext("2d");
    var piechart = new Chart(ctx).Pie(chartData);
  });
</script>

2 个解决方案

#1


0  

I figured it out! You have to use cookies to access the ID for the user, and here's a tutorial for that:

我想到了!您必须使用cookie来访问用户的ID,这里有一个教程:

http://www.w3schools.com/js/js_cookies.asp

#2


0  

The problem is that once you set the objectID variable, you navigate away from the page. Once you navigated away from the page, you can no longer access JS variables defined in the previous page.

问题是,一旦设置了objectID变量,就会离开页面。导航离开页面后,您将无法再访问上一页中定义的JS变量。

To go around this problem, you can store the value of the objectID so that the next page can access it again. You can do this using several methods.

要解决此问题,您可以存储objectID的值,以便下一页可以再次访问它。您可以使用多种方法执行此操作。

Using query parameters of the next page.

使用下一页的查询参数。

When redirecting to the logged in page, you can specify the objectID.

重定向到登录页面时,您可以指定objectID。

window.open("http://localhost/loggedIn.html?objectId="+objectID, "_self", true);

window.open(“http://localhost/loggedIn.html?objectId =”+ objectID,“_ self”,true);

Then, in the script in the loggedIn page, you can access the objectID using window.location.search

然后,在loggedIn页面的脚本中,您可以使用window.location.search访问objectID

console.log(window.location.search); // outputs ?objectId=2343

的console.log(window.location.search); //输出?objectId = 2343

Using localStorage

You can use localStorage to store the value of objectID. localStorage.setItem('objectID', objectID) then extract it in the logged in page using localStorage.getItem('objectID').

您可以使用localStorage存储objectID的值。 localStorage.setItem('objectID',objectID)然后使用localStorage.getItem('objectID')在登录页面中提取它。

Using Cookies

As you mentioned above, you can use cookies to store and extract the value of objectID. The disadvantage of this is that it is sent in all subsequent requests to the server.

如上所述,您可以使用cookie来存储和提取objectID的值。这样做的缺点是它会在所有后续请求中发送到服务器。

#1


0  

I figured it out! You have to use cookies to access the ID for the user, and here's a tutorial for that:

我想到了!您必须使用cookie来访问用户的ID,这里有一个教程:

http://www.w3schools.com/js/js_cookies.asp

#2


0  

The problem is that once you set the objectID variable, you navigate away from the page. Once you navigated away from the page, you can no longer access JS variables defined in the previous page.

问题是,一旦设置了objectID变量,就会离开页面。导航离开页面后,您将无法再访问上一页中定义的JS变量。

To go around this problem, you can store the value of the objectID so that the next page can access it again. You can do this using several methods.

要解决此问题,您可以存储objectID的值,以便下一页可以再次访问它。您可以使用多种方法执行此操作。

Using query parameters of the next page.

使用下一页的查询参数。

When redirecting to the logged in page, you can specify the objectID.

重定向到登录页面时,您可以指定objectID。

window.open("http://localhost/loggedIn.html?objectId="+objectID, "_self", true);

window.open(“http://localhost/loggedIn.html?objectId =”+ objectID,“_ self”,true);

Then, in the script in the loggedIn page, you can access the objectID using window.location.search

然后,在loggedIn页面的脚本中,您可以使用window.location.search访问objectID

console.log(window.location.search); // outputs ?objectId=2343

的console.log(window.location.search); //输出?objectId = 2343

Using localStorage

You can use localStorage to store the value of objectID. localStorage.setItem('objectID', objectID) then extract it in the logged in page using localStorage.getItem('objectID').

您可以使用localStorage存储objectID的值。 localStorage.setItem('objectID',objectID)然后使用localStorage.getItem('objectID')在登录页面中提取它。

Using Cookies

As you mentioned above, you can use cookies to store and extract the value of objectID. The disadvantage of this is that it is sent in all subsequent requests to the server.

如上所述,您可以使用cookie来存储和提取objectID的值。这样做的缺点是它会在所有后续请求中发送到服务器。