如何从java中的方法向javascript发送成功消息

How to send success message to javascript from a method in java?

本文关键字:javascript 成功 消息 方法 java      更新时间:2023-09-26

用户需要提供特定密码才能被授权访问特定页面。

我显示一个表单,如果用户输入了正确的密码将被重定向到新页面,否则需要显示一条消息,指示密码错误。我该如何实现它?

目前,我可以使用以下代码显示"错误密码"消息,但是如果密码正确,如何重定向用户。

如果我可以修改 xmlhttp 对象的返回代码,我可能能够满足要求。

function auth(){
    var form = $('#form').serialize();
    if(window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            document.getElementById("background").style.display = "Block";
            document.getElementById("box").style.display = "Block";
            document.getElementById("results").innerHTML=xmlhttp.responseText;
        } 
    }
    xmlhttp.open("get","../authenticate?"+form,false);
    xmlhttp.send();
    return false;
  }

爪哇岛

public String authenticate()
{
   if(user is authenticated)
      return a success parameter to JavaScript
   else
     return a wrong password message to JavaScript
}

其他信息

后端是Java。

我知道我可以使用 window.location.href 重定向,但需要确保在重定向之前对用户进行身份验证。

需要返回一个以成功作为其文本的页面,并使用以下

if(xmlhttp.responseText.trim() == 'Success')
            {
                 redirect code
            }
            else{
                     show error message
            }
 $.getJSON( url, myDataForTheServer)
    .done(function (dataReturned) {
      console.log(dataReturned);
    })
    .fail(function (response, status, statusText) {
      console.log(status + statusText);
    })
    .always(function () {
      console.log('the end');
    })

我认为您可以使用Java从后端对用户进行身份验证。

身份验证后,密码错误或正确。根据此结果,分别给出一个链接作为返回结果,并在会话或cookie中为当前用户设置状态。

当然,在呈现经过身份验证的页面时,您需要检查会话是否有效,以决定是否显示内容。

您可以使用php或asp或任何动态Web语言来寻求帮助。