我正在尝试通过JQuery AJAX向我的GAE应用发送POST请求,但我没有得到任何响应数据。我有一个非常简单的servlet,它只是回显我传入的“msg”。还覆盖了doOptions。
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
resp.setHeader("Access-Control-Max-Age", "1728000");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.setContentType("text/javascript");
resp.setCharacterEncoding("utf-8");
String msg = req.getParameter("msg");
resp.getWriter().print(msg);
}
以下是我通过JQuery AJAX调用的方法
var parameters = {msg:"hello"};
$.ajax({
type: 'POST',
url: service_url,
data: parameters,
success: successhandler,
error: errorhandler
})
如果我通过FireBug查看我的互动,我会看到这一点。
首先,JQuery发出OPTIONS请求
Host lessondesigner.appspot.com
User-Agent Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Origin lessondesigner.appspot.com
Access-Control-Request-Me... POST
Access-Control-Allow-Orig... *
Access-Control-Allow-Meth... GET, POST, OPTIONS
Access-Control-Max-Age 1728000
Date Mon, 06 Sep 2010 01:11:56 GMT
Content-Type text/html
Server Google Frontend
Content-Length 0
接下来发送POST请求
Host lessondesigner.appspot.com
User-Agent Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept application/json, text/javascript, */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Content-Type application/x-www-form-urlencoded; charset=UTF-8
Referer lessondesigner.appspot.com/testAjax.html
Content-Length 21
Origin lessondesigner.appspot.com
Pragma no-cache
Cache-Control no-cache
Content-Type text/javascript; charset=utf-8
Content-Encoding gzip
Date Mon, 06 Sep 2010 01:11:56 GMT
Server Google Frontend
Cache-Control private, x-gzip-ok=""
Content-Length 25
但是,我在回复中得不到任何回复!如果我使用Curl,它可以正常工作。
curl -d "msg=hello" lessondesigner.appspot.com/lessondesigner
我回来了
"hello"
有谁知道这是为什么?另外,为什么JQuery首先要执行OPTIONS请求?它甚至不是跨域的。
答案 0 :(得分:3)
想通了。这是跨源资源共享问题。这是一篇很棒的文章。
http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
基本上,如果HTTPRequest标头包含“origin”字段,则服务器必须使用“Access-Control-Allow-Origin”响应进行回复。就我而言,我在OPTIONS请求中执行此操作,但未在POST请求中执行此操作。因此firefox没有返回我的内容数据。为了解决这个问题,我必须这样做。
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setContentType("text/javascript");
resp.setCharacterEncoding("utf-8");
String msg = req.getParameter("msg");
resp.getWriter().print(msg);
}
答案 1 :(得分:-1)
尝试flushing作家