簡體   English   中英

動態表單操作網址

[英]Dynamic Form Action URL

我正在嘗試在我的網站上創建一個表單,其中用戶具有一個文本字段,他們可以使用該文本字段輸入注冊號。 我希望將注冊號添加到操作URL的末尾,以便在該頁面加載時可以使用PHP分解URL並獲取該號。 這是我正在尋找的示例...

<form action="http://mywebsite.com/registrations/123456789">
<input type="text" name="registrationnumber">
<input type="Submit" value="Submit">
</form>

是否有可能將輸入到注冊號文本字段中的任何內容傳遞給表單所指向的URL? 也許更簡單的方法是創建一個帶有按鈕的文本字段,單擊該按鈕時,通過在末尾添加注冊號來動態創建指向URL的鏈接。

有人知道這樣做的方法嗎?

實際上,您不需要表單即可進行AJAX調用。 一個簡單的輸入和按鈕就足夠了。

我已經制作了一個函數,該函數將進行AJAX調用,它將轉換包含要發送給PHP的參數的所有鍵/值對的對象params ,並將其連接為URL字符串:

function ajax(file, params, callback) {

  var url = file + '?';

  // loop through object and assemble the url
  var notFirst = false;
  for (var key in params) {
    if (params.hasOwnProperty(key)) {
      url += (notFirst ? '&' : '') + key + "=" + params[key];
    }
    notFirst = true;
  }

  // create a AJAX call with url as parameter
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      callback(xmlhttp.responseText);
    }
  };
  xmlhttp.open('GET', url, true);
  xmlhttp.send();
}

假設您有一個輸入字段:

<input id="code" type="text">
<button id="sendData">Send</button>

這是我們如何使用ajax函數的方法:

function sendData() {

  parameters = {
    inputValue: document.querySelector('#code').value
  };

  ajax('target.php', parameters, function(response) {
    // add here the code to be executed when data comes back to client side      
    // e.g. console.log(response) will show the AJAX response in the console
  });

}

然后可以使用事件偵聽器將按鈕附加到sendData

document.querySelector('#sendData').addEventListener('click', sendData)

暫無
暫無

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

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