从 Greasemonkey 到 Servlet 的 Ajax 调用:响应失败

Ajax call from Greasemonkey to a Servlet: response failure

本文关键字:调用 响应 失败 Ajax Greasemonkey Servlet      更新时间:2023-09-26

虽然我有编程经验,但对GS,JS或任何与UI相关的事物都是全新的。

场景:从 Greasemonkey 脚本到 Servlet 进行 AJAX 调用

Greasemonkey/JS Code:

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 Code:

        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");

问题:

  • 如果网址(在$.ajax中)是其他现有的API,则GS/JS代码可以完美运行。响应反映在 UI 中

  • 但是,当我提供服务器的网址时,我可以在Firebug.Console中观察到该调用没有http响应,但状态显示200 OK,整个条目变为"RED"。

  • 当我测试从Firebug的"http调用条目"复制的url时,它运行良好,因为我可以在新选项卡上看到响应"来自Servlet的文本"。

有人可以帮忙吗?

注意 运行 greasemonkey 的网站和我的服务器属于同一域,即

油脂猴网站: wwww.example.com

我的服务器:www.myserver.example.com

感谢@mattedgod。他的评论促使我进行更多的研究,我找到了答案。

添加以下代码片段以使其正常工作。

response.setHeader("Access-Control-Allow-Origin", "*");

令人惊讶的是,如果我在标头中明确指定我自己服务器的完整 http 地址,它不起作用。我还没有找出原因。