【问题标题】:Polling function with recurision, ajax具有递归、ajax 的轮询函数
【发布时间】:2016-04-21 11:35:40
【问题描述】:
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: 组件被调用是因为没有收到响应?

【问题讨论】:

    标签: jquery ajax servlets polling


    【解决方案1】:
    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 对象格式构成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 2013-03-22
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      • 2015-05-05
      相关资源
      最近更新 更多