轮回功能与recurision,ajax

时间:2016-04-21 11:35:41

标签: jquery ajax servlets polling

function poll() {
        setTimeout(function() {
        $.ajax({ 
            type: "GET",
            url: "GameLogic",
            contentType: "application/json", 
            data: {
                type: "update",
                card: JSON.stringify("string")
            },
            dataType: "json",
            success: function(data) {
                alert(JSON.stringify(data));
            },
            error: function(data) {
                alert('eroor');
            },
            complete: poll })
        }, 5000);
}

此函数应该每5秒发送一次请求并获得相应响应的警报。但它总是警告错误。请求由servlet处理。我检查并确认servlet正确接收请求。这是处理轮询请求的servlet代码。

String resp = "";
response.setContentType("application/json");  
PrintWriter out = response.getWriter(); 
if(request.getParameter("type").equals("update"))
{
    resp = "received";
}

out.write(resp);

我将resp字符串打印到服务器日志,它按预期工作。为什么服务器没有正确回复响应?调用error:组件是因为没有收到响应?

1 个答案:

答案 0 :(得分:0)

String resp = "";
response.setContentType("application/json");  
PrintWriter out = response.getWriter(); 
if(request.getParameter("type").equals("update"))
{
    JSONObject mainObject = new JSONObject();
    mainObject.put("value","received");
    resp = mainObject.toString();
}

out.write(resp);

由于内容类型设置为“application / json”,resp字符串应该由json对象格式构成。