简体   繁体   中英

Saving var using JavaScript and redirecting to URL

I have a very simple web form containing two input fields and a submit button.

What I would like to do is save the two strings inserted and redirect to my other HTML file (which is in the same folder).

HTML:

<!DOCTYPE html>
<html>
<title>Players enter</title>
<head>
<script type="text/javascript" src="ticTac.js"></script> 
<link rel="stylesheet" type="text/css" href=styleSheet.css></link>

</head>
<body>
 <form >
      player one name: <input type="text" id="firstname"><br>
      player two name: <input type="text" id="secondname"><br>
      <input type="submit" onclick="checkNames();"/>
</form>

</body>
</html>

JavaScript:

function checkNames(){
    var nameOne = document.getElementById("firstname").value;
    var nameTwo = document.getElementById("secondname").value;
    //window.location.href = 'C:\Users\x\Desktop\hw3\tic\Game.html';
    //window.location.replace("C:\Users\x\Desktop\hw3\tic\Game.html");
    window.location.assign("C:\Users\x\Desktop\hw3\tic\Game.html");
}

I have commented the two other options I tried which also do not work.

To redirect to a page in your computer you can use:

window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html';

There are more than one way of passing the values to another page. Here is an example using query string.

In the page that has the values.

var q = '?nameOne=' + encodeURI(nameOne) + '&nameTwo=' + encodeURI(nameTwo)
window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html' + q;

In the page receiving the values.

var nameOne = location.search.slice(1).split("&")[0].split("=")[1];
var nameTwo = location.search.slice(1).split("&")[1].split("=")[1];

You are using an HTML form... this means that your submit button will fire and try to submit your form.

In order to prevent this, you need to prevent that event from triggering. A simple modification to your JavaScript function should do the trick.

function checkNames() {

        event.preventDefault();
        var nameOne = document.getElementById("firstname").value;
        var nameTwo = document.getElementById("secondname").value;
        window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html';

}

使用window.location =“ url”;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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