$('#loginForm').submit(function(e){
var $inputs = $(this).find("input");
var serializedData = $(this).serialize();
$inputs.prop("disabled", true);
var request = $.ajax({
url: "myurl",
dataType: "json",
type: "GET",
data: serializedData,
});
request.done(function (response, textStatus, jqXHR){
$('#loginMessage').text('GOOD');
});
request.fail(function (jqXHR, textStatus, errorThrown){
$('#loginMessage').text('Some error occured. Please try again');
console.error("The following error occured: ",errorThrown,jqXHR);
});
request.always(function () {
$inputs.prop("disabled", false);
});
// prevent default posting of form
e.preventDefault();
});
我是jquery的新手,在上面的代码中.done块没有执行,firebug控制台显示这条消息: -
GET myurl?userID=aman&password=aman
200 OK 37ms jquery .... min.js(第2行)
发生以下错误:(空字符串)Object { readyState=0, status=0, statusText="error"}
服务器端脚本
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("userID");
String password = request.getParameter("password");
System.out.println("GET");
response.setContentType("application/json");
PrintWriter out = response.getWriter();
Gson gson = new Gson();
if(username.equals("aman") && password.equals("aman")){
out.println(gson.toJson(new Boolean("true")));
}else{
out.println(gson.toJson(new Boolean("false")));
}
out.close();
}
答案 0 :(得分:5)
问题可能是您没有发送完整的JSON。我从
输出结果out.println(gson.toJson(new Boolean("true")));
你得到的只是真实的。尝试将其更改为类似的内容。
HashMap<String, Boolean> hm = new HashMap<String, Boolean>();
hm.put("success", true);
out.write(gson.toJson(hm));
运行我得到{“success”:true}这是有效的JSON。
答案 1 :(得分:2)
可能不会调用,因为会调用fail。 由于http请求本身似乎有效,另一个可能的问题是它没有返回正确的json内容,而回复被解释为这样(因为dataType:“json”)。
因此,您应该调查服务器返回的内容。
答案 2 :(得分:0)
我不知道为什么,但有时候firebug断点给人的印象是request.done()中的代码没有被执行。也许它只是简单地引导到控制台。
尝试在firebug中测试没有断点的代码。