虽然我有编程经验,但对 GS、JS 或与 UI 相关的任何东西都是全新的。
场景:从 Greasemonkey 脚本向 Servlet 发起 AJAX 调用
Greasemonkey/JS 代码:
function getResultsData(query){
alert("Getting the Data");
$.ajax(
{
cache: false,
data: {"q":query},
dataType:"text",
url: "http://myserver.com:8000/search?",
success: processData
}); //end of $.ajax }
function processData(data){
alert("Got the data");
var myResultDiv = document.getElementById("searchRes");
myResultDiv.innerHTML = data; }
Servlet 代码:
System.out.println("-----------This is an AJAX call------------------");
//Commented the original logic
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write("Text from Servlet");
问题:
如果 url(在 $.ajax 中)是其他一些现有 API,GS/JS 代码将完美运行。响应反射(reflect)在 UI 中
但是,当我提供服务器的 URL 时,我可以在 Firebug.Console 中观察到该调用没有 http 响应,但状态显示 200 OK,整个条目变为“RED”。
当我测试从 Firebug 的“http 调用条目”复制的 url 时,它工作正常,因为我可以在新选项卡上看到响应“来自 Servlet 的文本”。
有人可以帮忙吗?
注意 运行 greasemonkey 的网站和我的服务器属于同一个域,即
Greasemonkey 网站:wwww.example.com
我的服务器:www.myserver.example.com
最佳答案
感谢@mattedgod。他的评论促使我进行更多研究,我找到了答案。
添加以下代码片段以使其工作。
response.setHeader("Access-Control-Allow-Origin", "*");
令人惊讶的是,如果我在 header 中明确指定我自己的服务器的完整 http 地址,它就不起作用。我还没有找出原因。
关于javascript - 从 Greasemonkey 到 Servlet 的 Ajax 调用 : response failure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11269320/