2012-08-22 74 views
0

我有下面的代碼片段:JavaScript的Ajax請求的servlet調用錯誤回調函數

$(d).ready(function() { 
    $.ajax({ 
     url : "http://localhost:8080/ProjTest/TestServlet", 
     type : "POST", 
     dataType : "text", 
     data : { test : "test" }, 
     error : function() { 
      alert(1); 
     }, 
     success : function(data) { 
      alert(2); 
     } 
    }); 
}); 

,並在我的servlet:

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { 
    Printer out = res.getWriter(); 
    String paramTest = req.getParameter("test"); 
    System.out.println("1"); 
    out.print(paramTest); 
    out.close(); 
    System.out.println("2"); 
} 

當我運行,在控制檯:

1 
2 

但是,在javascript調用錯誤函數!!!

任何想法???


解決:

我改變了servlet來

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { 
    res.setHeader("Access-Control-Allow-Origin", "*"); 
    Printer out = res.getWriter(); 
    String paramTest = req.getParameter("test"); 
    System.out.println("1"); 
    out.print(paramTest); 
    out.close(); 
    System.out.println("2"); 
} 

我增加了行:

res.setHeader( 「訪問控制允許來源」,「 *「);

+0

請從問題中刪除'Solved'部分也去掉'解決: '從標題中。將「已解決」部分作爲您的問題的答案,然後接受答案。這將有助於社區知道這個問題的答案,並幫助遵循標準。謝謝 –

回答

3

有後面沒有逗號的{}data

dataType : "text", 
data : { test : "test" } 
// No comma here --------^ 
error : function() { 

它應該是這樣的:

dataType : "text", 
data : { test : "test" }, // <--- can you see the comma :-D 
error : function() { 
+0

編輯您的帖子,以顯示正確的語法,而不是指出來;) –

+0

謝謝,但即使如此,仍然無法正常工作... –

+0

@CaioFrota嘗試清除更改後的瀏覽器緩存。 –