database query via javascript & servlet

database query via javascript & servlet

本文关键字:amp servlet javascript query via database      更新时间:2023-09-26

我正试图通过html页面从数据库中查询信息。我已经让所有的后台工作正常,但我在客户端遇到了麻烦。我目前有一个表单,用户可以在其中提交他们的ID#,以获取有关他们案件的一些信息。

但在我目前的设置中,它会返回一个全新的页面,我只想读入一个文本字符串,处理它并更新当前html页面上的内容,而不需要打开新页面并替换旧页面。如何做到这一点?

到目前为止,这是我的代码:

function showInfo() { } // I want to make the request here instead
<form name="register" action="http://localhost:8080/testapp/authenticate" method="get">
      <p><label for="badge">ID #:</label>
         <input id="badge" name="ID" type="text" pattern="[0-9]{6}"
                placeholder="xxxxxx">
         <button id="checkButton" type="submit" onClick="showInfo()">Enter</button>   
      </p>
    </form>

我的猜测是,您实际上是在提交表单,并将其发布回服务器。你想做的是取消表单的提交,并使用AJAX提交(我相信这就是你想要的?)。

要做到这一点,showInfo()函数应该做以下三件事中的一件(我永远记不清是哪一件了)

  1. return false;
  2. 取消活动,类似e.preventDefault()
  3. 停止传播,类似于e.stopPropagation()

一旦你成功地阻止了表单的硬提交,你就可以通过AJAX提交你的数据,并根据你的意愿操纵你的响应。

1st-Jason说得对,在这种情况下你想要的是AJAX,下面是一个动态的例子。

第二-你应该使用像jQuery这样的Javascript库,这可能看起来很吓人(就像一开始对我所做的那样),但它真的很容易,而且完全值得花点小力气来实现。

第三-使用jQuery,您的应用程序花絮应该是这样的,使用您提供的示例:

HTML-

    <p>
        <label for="badge">ID #:</label>
        <input id="badge" name="ID" type="text" pattern="[0-9]{6}"
            placeholder="xxxxxx">
        // Please note that I removed the onClick section from the line below.
        <button id="checkButton" type="button">Enter</button>   
    </p>

JQUERY-

// The default function you described to take information and display it.
function showInfo(data) {
    // Insert your function here, probably using JSON as the Content Type
}
// This is the key AJAX function, using jQuery, that takes your info and gets a    
// response from the server side, the sends it to the function above in order for it 
// to be displayed on the page.
function processIdInfoCheck() {
    $.ajax({
        type: 'post',
        url: '/http://localhost:8080/testapp/authenticate',
        data: { 
           'id': $('#badge').val();
        },
        dataType: 'json',
        success: displayIdInfoReturn,
        error: function () {
            alert("There was an error processing your request, please try again");
        }
    });
}
// When the page loads, the code below will trigger, and bind your button click        
// with the action you want, namely triggering the AJAX function above
(function ($) { 
    $('#checkButton').bind('click', processIdInfoCheck);
})(jQuery);

请记住,AJAX需要付出一些努力才能获得所需的效果,但当你看到页面加载时间、请求数量等时……这完全值得。请告诉我这是否有帮助,如果你需要任何细节。