Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

How to pass data to parent in JavaScript and HTML

I am creating a website in plain HTML, CSS and JavaScript and want to send data between two pages (child and parent). Here is a simple example of what I want to do. CHILD PAGE:

<html>
<head>
<title>Child</title>
</head>
<body>
<input type='text' placeholder='Enter data to be sent.' id='data'>
<button onclick='work()'>Send</button>
<script>
function work(){
var data = document.getElementbyId('data').value
//Code to send this data to parent.
}
</body>
</html>

PARENT PAGE:

<html>
<head>
<title>Parent</title>
</head>
<body>
<h1 id='data_recieved'></h1>
<button onclick='work()'>Recieve</button>
<script>
function work(){
var data = document.getElementbyId('data_recieved').innerHTML;
//Code to receive the data from child
}
</body>
</html>

I will be very grateful for your help.

question from:https://stackoverflow.com/questions/65904750/how-to-pass-data-to-parent-in-javascript-and-html

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

DOM don't work across pages. You have to use a storage medium, it can be client side i.e localStorage, 'sessionStorage' or cookies using JavaScript. Or you can use a backend where you can store the values in some sort of database.

Another way to pass data from one page to another is to use a <form>, fill in certain fields and submit it so that it gets sent as POST or GET data to the next page. In your case I believe this should be the ideal scenario. If you do not have a backend best option is to send form data using GET method so that it gets appended to the URL as query parameters.

e.g on parent HTML page

<form action='child.html' method='get'>
   <input type='text' name='somedata' value='whatever'/>
   <input type='submit'/>
</form>

and on child page you can use JavaScript to get the query parameters using JS

<script>
var somedata = getParameterByName('somedata');
function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[[]]/g, '\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/+/g, ' '));
}
</script>

There are of course other more sophisticated and advanced ways to achieve the same results but those might not be what you are looking for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...