我需要将li1和li2读取的vaule发送到验证用户的servlet(没有DB调用),并且servlet以true或false响应。这个布尔值必须在我的.js文件中读取并且必须改变只有DOM结构没有重新加载整个页面,以防无效用户使用适当的消息。
我的logintom.js如下
goog.require('goog.dom');
goog.require('goog.events.EventType');
goog.require('goog.style');
goog.require('goog.ui.Control');
goog.require('goog.ui.Button');
goog.require('goog.ui.FlatButtonRenderer');
goog.require('goog.ui.LabelInput');
goog.require("goog.net.XhrIo");
goog.require("goog.structs.Map");
goog.require("goog.Uri.QueryData");
function setUp() {
var li1 = new goog.ui.LabelInput('USER NAME');
li1.render(goog.dom.getElement('d1'));
var li2 = new goog.ui.LabelInput('PASSWORD');
li2.render(goog.dom.getElement('d2'));
var val1;
var val2;
var fb1 = new goog.ui.Button('Login',goog.ui.FlatButtonRenderer.getInstance());
fb1.render(goog.dom.getElement('fb1'));
goog.events.listen(fb1,goog.ui.Component.EventType.ACTION,
function(e) {
val1 = li1.getValue();
val2 = li2.getValue();
var request = new goog.net.XhrIo();
goog.events.listen(request, "complete", function(){
if (request.isSuccess())
{
console.log("Satus code: ", request.getStatus(), " - ", request.getStatusText());
}
else {
console.log("Something went wrong in the ajax call. Error code: ", request.getLastErrorCode()," - message: ", request.getLastError());
}
});
var param = 'username='+val1+'&password='+val2;
var url = 'loginprocessortom?username='+val1+'&password='+val2;
request.send(url, "POST");
});
}
我的Servlet如下
public class loginprocessortom extends HttpServlet
{
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException
{
String uname = (req.getParameter("username"));
String pword = (req.getParameter("password"));
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
if (uname == "xyz" && pword == "xyz")
{
tof = true;
}
else
{
tof = false;
}
}
}
我的HTML如下。
<html>
<head>
<script src="closure-library/closure/goog/base.js"></script>
<script src="logintom.js"></script>
</head>
<body onload="setUp();">
<fieldset>
<legend>
<strong>Authentication</strong>
</legend>
<div id="d1">User Name   </div>
<br>
<div id="d2">Password    
</div>
<br>
<div id="fb1"></div>
<br>
<span id="sp1"></span>
</fieldset>
</body>
</html>
我需要将这个“tof”发送到我的.js,我可以根据“tof”的值使用闭包和更改页面来读取它而无需重新加载整个页面(Ajax行为)
答案 0 :(得分:0)
goog.events.listen(request, "complete", function(e){
var xhr = /** @type {goog.net.XhrIo} */ (e.target);
res = xhr.getResponseText();
if(xhr.getResponseText() == "true")
{
goog.dom.getElement("sp1").innerHTML = ("Hi Welcome");
}
else
{
goog.dom.getElement("sp1").innerHTML = ("Invalid Username or Password");
}
});
使用上面的代码替换控制台日志功能应该可以。