我有以下代码片段:
$(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("Access-Control-Allow-Origin", "*");