javascript - HTML 页面和 Java servlet 之间交换数据,无需刷新页面

标签 javascript java json servlets

我想使用 HTML 和 Java(也许还有 JSON)创建一个简单的登录表单。因此,我有一个登录表单,其中包含多个输入字段,其中包含以下 id-s:txtUsername、txtPasswd、btnLogin。 单击按钮(btnLogin)后,我想将数据发送到servlet,并返回用户密码组合加深的真/假值。 我可以编写这种形式的HTML代码,以及服务器端代码,但我不知道,如何在不刷新页面的情况下发送和接收数据。

这是我的前端代码:

<script>
   function login(){
       var user=document.getElementById("txtUsername");
       var passwd=document.getElementById("txtPasswd");
         //???
   }
</script>


Username: <input type="text" id="txtUsername"/> <br/>
Password: <input type="password" id="txtPasswd"/> <br/>
<input type="button" value="Login" id="btnLogin" onclick="login()"/>

最佳答案

您必须使用 AJAX 请求。一种方法是在您的 login 按钮(如 onclick)上连接事件处理程序,该按钮调用 JS 函数来使用 Ajax request (XmlHttpRequest),就像您开始时一样。

您可以使用普通的 Javascript 来完成此操作,但使用像 jQuery 这样的库会更容易。代码看起来像这样(使用 jQuery,注意“$”):

function login() {
    $.ajax({
        type: 'POST',
        url: url, //Url of login endpoint
        data: DATA, //Now here you would want to send a payload i.e. your username and password data
        dataType: 'json',
        contentType: 'application/.json',
        success: function(data) { 
                    //HERE 'data' would represent your true or false that came back from the server. 
                    //You can do stuff here with the response
                 },
        error: function(jqXHR, textStatus, errorThrown) {
                    //IF ERROR then this code would be executed.                        
               }
    });
}

希望这能为您提供一个起点!

关于javascript - HTML 页面和 Java servlet 之间交换数据,无需刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40613304/

相关文章:

javascript - 合并 JavaScript 文件的版权问题?

java - 斐波那契迭代 : To find the nth term of the Fibonacci sequence for n > 50

javascript - d3js 在编码解码数据后工作

json - 搜索Youtube并返回JSON

json - 如何从另一个模式引用 json 模式定义

javascript - d3 绘图太大,无法包含 div

javascript - 模式中的按钮不起作用

javascript - 网络音频频率限制?

用于构建 SQL 前端 GUI 的 Java 库\应用程序

java - 使用 GridBagLayout JTables 和 JScrollPane 不起作用