簡體   English   中英

使用javascript單擊下拉列表值后,在URL中傳遞表單數據?

[英]Pass the form data in the URL after clicking on the drop down list values using javascript?

我的形式如下:我使用 nodejs 和 javascript。這里取決於用戶從下拉列表中選擇的值,相應地調用該 url。例如電影選項:“localhost:3000/new”將被調用.這很好用! 但它只是在沒有任何表單參數的情況下重定向到 url。我希望表單值也與 url 一起傳遞。如何做到這一點? 請幫忙? 謝謝 :)

   <form>
  <input type="text"  name="currentloc" class="textbox" id="currentloc"  
placeholder="Your location"/>
<input type="text" name="destloc" id="destloc"  autofocus="autofocus" 
class="textbox" placeholder="Enter the destination"/>     
First Event : <select name="events" onchange="location = this.value;">
  <option value="" >Select your first event</option><br><br>
  <option  value="/new" name="movies" id="movie" method="get">Watch a 
Movie</option>
  <option value="/food" name="restuarantis" id="rest" >Restaurant table 
 booking</option>
 </select>
</form>

以下是您可以在表單中執行的操作:

<body>
    <form name="pickerForm" method="GET" action="">
        <input type="text" name="currentloc" class="textbox" id="currentloc" placeholder="Your location" />

        <input type="text" name="destloc" id="destloc" autofocus="autofocus" class="textbox" placeholder="Enter the destination" />

        First Event :
        <select name="events" onchange="return loadCorrectPage(event);">
            <option value="" >Select your first event</option><br><br>
            <option value="/new" name="movies" id="movie" method="get">Watch a Movie</option>
            <option value="/food" name="restuarantis" id="rest" >Restaurant table booking</option>
        </select>
    </form>

    <script>
        function loadCorrectPage(event) {
            event.preventDefault();
            console.log(event.target.value);
            document.forms['pickerForm'].action = event.target.value;
            document.forms['pickerForm'].submit();
        }
    </script>
</body>
  1. document.forms['pickerForm']匹配表單元素<form name="pickerForm"因為name=
  2. 您必須使用method="GET"將表單中的數據發送到您的 node.js 后端並使它們在req.queryreq.query
  3. 我們使用action=""因為我們將使用 JavaScript 設置它
  4. 當您的select元素發生變化時,我們運行函數loadCorrectPage()並傳入event ,它是一個保存有關 onchange 事件數據的變量
  5. 然后,我們需要創建函數
  6. event.preventDefault()在這里可能是不必要的,但如果你不這樣做,了解它是如何工作的很好
  7. event.target.value保存更改選項的值
  8. 我們將document.forms['pickerForm'].action更新為更改后的選項,這意味着action=""現在是action="/new"action="/food"
  9. 我們調用document.forms['pickerForm'].submit()來提交表單!

現在,在您的 node.js 后端,您需要相應的路由。 如果您使用 Express,它們將如下所示:

app.get('/new', function(req, res) {
    console.log('\nSomeone just picked movies!');
    console.log('Current location:', req.query.currentloc);
    console.log('Destination:', req.query.destloc);
});

app.get('/food', function(req, res) {
    console.log('\nSomeone just picked restaurants!');
    console.log('Current location:', req.query.currentloc);
    console.log('Destination:', req.query.destloc);
});

暫無
暫無

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

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