簡體   English   中英

如何在不刪除數據的情況下使用 onsubmit 轉到另一個 html 頁面

[英]How to go to another html page with onsubmit without erasing data

我的代碼將不起作用,因為我試圖讓我的值在保留它們的同時提交到另一個 html 頁面。 如果我把return false; 它將轉到下一個 HTML 頁面而不保留值; 如果我沒有它,它會保留值而無需轉到下一頁。 如果這實際上可行,請提供幫助,如果不可行,請給我其他建議。

 document.getElementById('form').onsubmit = function(e) { class matches { constructor(name1, name2) { this.name1 = name1; this.name2 = name2; } } const p1 = document.querySelector('#person1').value; const p2 = document.querySelector('#person2').value; const pair = new matches(p1, p2); console.log(`${pair.name1} and ${pair.name2}`); return false; };
 <div id="main-header"> <h1>Ship It! &#10085;</h1> </div> <div id="container"> <div id="title"> <h1>What is your magical Ship?</h1> <form action="pages/lodaing.html" id="form"> <input type="text" placeholder="Your Firstname" id="person1" autocomplete="off"> <input type="text" placeholder="Their Firstname" id="person2" autocomplete="off"><br> <a href="/pages/lodaing.html"><button id="button" type="submit"><a href="/pages/lodaing.html"onclick="">&#9829</a></button> </a> </form> </div> </div>

如果我需要添加任何其他內容,請通知我。 抱歉,如果我沒有使用正確的術語(我是這項工作的新手)。

謝謝!

  1. 移除onSubmit事件監聽器的代碼
  2. 將 name 屬性添加到您的input元素

HTML [當前頁面]

<form action="pages/lodaing.html" id="form"> 
    <input type="text" placeholder="Your Firstname" name="person1"
                    autocomplete="off">
    <input type="text" placeholder="Their Firstname" name="person2" autocomplete="off"><br>
    <button id="button" type="submit">Submit</button>
</form>
  1. 您可以編寫以下代碼以獲取下一頁上兩個輸入的輸入值

JS [下一頁]

function getParameterByName(name, url) {
    if (!url) 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, ' '));
}

var person1 = getParameterByName('person1');
var person2 = getParameterByName('person2');

console.log(person1,person2);

解釋

這里發生的事情是,

當前頁面 [HTML] 上的表單在“pages/lodaing.html”上提交獲取請求

當使用“Get”方法提交表單時[這是默認值],新頁面加載表單值作為從表單輸入創建的查詢參數[?param1=value1&param2=value2]

因此,我們編寫了一些腳本來從下一頁的 url 中獲取確切的參數值

在 Javascript 函數內部,我們傳遞需要獲取提交值的參數名稱

該函數解析模式的 url 字符串並搜索我們傳遞的鍵並返回相同的值

希望這對您來說很容易理解!

讓您的表單通過 GET 方法(這是默認方法)發送值,您可以在下一頁使用 Javascript URLSearchParams對象,該對象具有處理傳遞的數據所需的一切。 使用此對象,您可以避免在第一頁上使用 Javascript 代碼,除非您當然需要特定的數據檢查和/或操作。

在此處查看URLSearchParams

注意:在您的代碼中,您必須為要傳遞給其他 HTML 頁面的值的輸入字段指定屬性名稱,因為表單不會發送任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM