Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - passing form data to another HTML page

I have two HTML pages: form.html and display.html. In form.html, there is a form:

<form action="display.html">
    <input type="text" name="serialNumber" />
    <input type="submit" value="Submit" />
</form>

The form data is sent to display.html. I want to display and use the form data serialNumber in display.html, as shown below:

<body>
    <div id="write">
        <p>The serial number is: </p>
    </div>
    <script>
    function show() {
        document.getElementById("write").innerHTML = serialNumber;
    }
    </script>
</body>

So how can I pass the serialNumber variable from form.html to display.html so that the above code in display.html will show the serial number and the JavaScript function show() gets the serialNumber from the first HTML?


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

1 Answer

0 votes
by (71.8m points)

If you have no option to use server-side programming, such as PHP, you could use the query string, or GET parameters.

In the form, add a method="GET" attribute:

<form action="display.html" method="GET">
    <input type="text" name="serialNumber" />
    <input type="submit" value="Submit" />
</form>

When they submit this form, the user will be directed to an address which includes the serialNumber value as a parameter. Something like:

http://www.example.com/display.html?serialNumber=XYZ

You should then be able to parse the query string - which will contain the serialNumber parameter value - from JavaScript, using the window.location.search value:

// from display.html
document.getElementById("write").innerHTML = window.location.search; // you will have to parse
                                                                     // the query string to extract the
                                                                     // parameter you need

See also JavaScript query string.


The alternative is to store the values in cookies when the form is submit and read them out of the cookies again once the display.html page loads.

See also How to use JavaScript to fill a form on another page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.7k users

...