2016-04-21 86 views
0
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代碼。輪詢功能,ajax

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

out.write(resp); 

我將resp字符串打印到服務器日誌中,並按預期工作。爲什麼服務器沒有正確回覆答覆? error:組件被調用是因爲沒有收到響應?

回答

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對象格式來製備。