【问题标题】:jQuery cors ajax request failingjQuery cors ajax 请求失败
【发布时间】:2013-12-06 06:31:51
【问题描述】:

我正在尝试使用 jQuery 向同一台机器中的不同端口发出 cors ajax 请求,下面是我的代码(我的应用程序在端口 80 上的 appache 服务器上运行):

JS:

$(function(){
    jQuery.support.cors = true;
    $.ajax({
        type: "POST",
        url: "http://127.0.0.1:8080/sys_monitor/ccn",
        dataType: "text",
        contentType: "text/plain",
        data : {a: '11'},
        success : function(res){
            alert(res);
            $('#stage').html(res);
        },
        error : function(jqXHR, text, exception){
            if (jqXHR.status === 0) {
                alert ('Not connected.\nPlease verify your network connection.');
            } else if (jqXHR.status == 404) {
                alert ('The requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert ('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert ('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert ('Time out error.');
            } else if (exception === 'abort') {
                alert ('Ajax request aborted.');
            } else {
                alert ('Uncaught Error.\n' + jqXHR.responseText);
            }
        }
    });
        });

在 8080 端口上运行在 tomcat (eclipse) 上的 Servlet(“post”被写入控制台):

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.getWriter().write("hello there");
    System.out.println("post");
}

使用 firebug 我可以看到请求(响应代码为 200)和内容长度 11(空结果选项卡),但错误函数正在以 XHR 状态 0 执行

(附带问题1:为什么萤火虫将“xml”显示为类型?):

(附带问题2:为什么在 POST 之前没有 OPTIONS 请求?):

我也尝试使用 RESTClient 插件 for firefox,我得到了想要的结果:

欢迎所有帮助/提示

【问题讨论】:

  • 那么,您是否真的启用了 CORS?
  • 我们如何做到这一点?我认为这一行 jQuery.support.cors = true; 会做到这一点
  • 您在 Chrome 上运行时是否得到相同的行为,XHR 对象需要读取 HTTP 状态响应才能返回正确的(状态)代码。我怀疑当你在本地机器上时会发生这种情况
  • 感谢@DavidFregoli,这很尴尬,我已经访问过那个网站但没有注意它:p; doPost 方法中的 response.addHeader("Access-Control-Allow-Origin", "*"); 行将解决该问题。请将此作为答案,以便我接受。 PS:关于附带问题的任何想法?

标签: java jquery ajax servlets cors


【解决方案1】:

检查这个问题 XmlHttp Request status 0, localhost issues (javascript, ajax, php) help,

看起来像是处理本地主机的浏览器问题

【讨论】:

  • 您引用的问题涉及意外的跨域调用。这根本不是这里发生的事情。
  • 确实与跨域调用有关,与浏览器的实现有关
猜你喜欢
  • 2021-11-19
  • 1970-01-01
  • 2013-05-18
  • 2015-12-15
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多