【发布时间】:2011-03-03 12:35:36
【问题描述】:
在下面的代码中,我向以这种方式回复的 servlet 发出 POST 请求:
response.setContentType("application/json");
json = "{success:true,sessionUid:\""+sessionUid+"\"}";
response.getWriter().write(json);
所以 Firefox 像打开文件一样打开它,我可以看到它没问题。这里有 JSON:
{success:true,sessionUid:"D07WC15R7LFRFRGPF4P5"}
问题是我无法检查 JSON 对象。它似乎不存在于我的回调函数中(也使用 Firebug)。查看代码和警报。
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#loginForm").submit(function(response){
alert("response="+response); //output: "response=[object Object]"
var obj = jQuery.parseJSON(response);
alert("obj.sessionUid="+obj.sessionUid); //doesn't work, Firebug says "obj is null"
if (response.success == true){ //never true
document.location.href = 'http://localhost:8080/QuoteroClient/logged.jsp';
}else{
alert("Something went wrong in the login process.");
}
return false;
});
});
</script>
</head>
<body>
<form id="loginForm" action="http://localhost:8080/QuoteroClient/Main?servlet=Security" method="post">
<fieldset><legend>Login to Quotero:</legend>
<label>Action:</label><input type="text" name="action" value="login"/><br />
<label>Username:</label><input type="text" name="login-quotero" value="admin"/><br />
<label>Password:</label><input type="text" name="password-quotero" value="admin" /><br />
<label>Domain:</label><input type="text" name="combo-domain" value="Quotero" /><br />
</fieldset>
<input type="submit" value="Submit" />
</form>
</body>
</html>
编辑:我也尝试对 AJAX 请求做同样的事情,但没有成功:
$("#ajaxSubmit").click(function () {
$.ajax({
type: "GET", //GET or POST is the same for this servlet
url: "http://localhost:8080/QuoteroClient/Main?servlet=Security&action=login&login-quotero=admin&password-quotero=admin&combo-domain=Quotero",
dataType: "json",
success: function (response) {
alert("response=" + response);
var obj = jQuery.parseJSON("" + response);
alert("obj.sessionUid=" + obj.sessionUid);
if (response.success == true) {
document.location.href = contextPath + 'http://localhost:8080/QuoteroClient/logged.jsp';
} else {
alert("Something went wrong in the login process.");
}
}
});
return false;
});
【问题讨论】:
-
我不明白如果你使用萤火虫为什么要使用
alert()?使用console.log(response);这样您就可以像文件树一样查看甚至导航json对象 -
我认为你的问题可能在这条线上
var obj = jQuery.parseJSON(response);我认为响应返回为 jquery 反正不需要再次解析它。 -
您是否要将此作为 ajax 请求?因为否则提交只是一个事件处理程序而不是 ajax 请求。
-
@Val 感谢console.log(),对我来说是新东西!我尝试将其作为 AJAX 请求进行,但没有成功。现在我尝试编辑问题。
-
删除
?servlet=Security&action=login&login-quotero=admin&password-quotero=admin&combo-domain=Quotero并使用data选项在我的回答告诉你如何serialize它,也看看serializeArray
标签: javascript jquery json response