2017-07-01 30 views
0

我在JSP文件中有一個文本框。當用戶在文本框中輸入郵編時,它應該去api的url並根據需要提供必要的數據。如何在JSP中使用REST Api?

REST Api已準備就緒,所有內容均已設置。我只想知道如何將我的請求發送到網址。

+0

您是否希望通過瀏覽器完成此操作,以便以交互方式或在服務器上完成? –

+0

在服務器上@ErwinBolwidt – Tatkal

+0

https://stackoverflow.com/a/14185607/7113238可能會有所幫助。 – Lawliet

回答

0

如果我正確理解問題,則在視圖中使用文本框(使用JSP模板呈現該文本框)。只要用戶在文本框中輸入郵政編碼,就需要向服務器發送請求並獲取數據。

這可以通過在前端使用JavaScript調用AJAX來實現(我在這裏使用jquery來簡化事情)。在JSP標記之間把這個在:

BASE_URL = "http://server_url/" // Your REST interface URL goes here 

$(".postcode-input button").click(function() { 
    var postcode = $(this).parents(".postcode-input") 
     .children("input").val(); 
    // First do some basic validation of the postcode like 
    // correct format etc. 
    if (!validatePostcode(postcode)) { 
     alert("Invalid Postal Code, please try again"); 
     return false; 
    } 
    var finalUrl = BASE_URL += "?postcode=" + postcode; 
    $.ajax({ 
     url: finalUrl, 
     cache: false, 
     success: function (html) { 
      // Parse the recieved data here. 
      console.log(html); 
     } 
    }); 
}); 

使用的輸入元素是這樣的:

<div class="postcode-input"> 
    <input type="text" maxlength="6"> 
    <button type="submit"></button> 
</div> 

上面的代碼發送GET請求,你同樣可以發送POST請求。有關更多信息,請參閱jQuery AJAX docs