【问题标题】:Jquery ajax call returns error when the rest service is returning a string当其余服务返回字符串时,Jquery ajax 调用返回错误
【发布时间】:2013-06-04 01:24:27
【问题描述】:

尝试从我的休息服务发送一个简单的文本并使用 ajax 调用读取它。找到了很多关于 jsonp 和跨浏览器兼容性的答案,也尝试过跨域。

这里是休息服务: 修剪所有内容以仅发送一个简单的字符串。

@GET
@Path("/getcontents2")
@Produces({MediaType.TEXT_PLAIN})
public String getContents2(@QueryParam("name") String msg) {
  return "abc";
}

ajax 调用:

$(document).ready(function() {
  $.ajax({
    type: 'GET',
    url: 'http://metrics/getcontents2?name=Work/loc.txt',
    crossDomain: true,
    async: false,
    dataType:'html',
    success: function (data) {
      console.log(data);
    },
    error: function (xhr, ajaxOptions, thrownError) {
      console.log(xhr.status);
      console.log(thrownError);
      console.log(xhr.responseText);
      console.log(xhr);
    },
  });
});

浏览器按原样打开字符串。我猜 jquery 脚本确实有问题。

Firebug 错误:

GET http://metrics/getcontents2?name=Work/loc.txt 200 OK 4ms    
0 
(an empty string) 
(an empty string) 
Object { readyState=0, status=0, statusText="error"} 

【问题讨论】:

    标签: java jquery ajax rest


    【解决方案1】:

    修好了!

    这是因为我的服务器不支持跨域。配置它会 corsfilter,它就像一个魅力!

    【讨论】:

    • 遇到了几乎相同的问题。我的网页在本地主机上,但网络服务在服务器上。
    【解决方案2】:

    尝试将您的数据类型设置为 text jsonp

    dataType: 'jsonp',
    

    http://api.jquery.com/jQuery.ajax/

    您必须执行以下两项操作之一才能进一步解决错误;

    1. 在服务器端进行更改以将数据作为 json 而不是文本传回
    2. 重新调整json编码的字符串return "{"text":"abc"}"; //or something like this

    为什么?

    jquery 跨域请求只允许对数据类型“script”和“jsonp”。

    我已经更新了你的 fiddle 它仍然会抛出一个错误,但这与解析 json 错误有关

    【讨论】:

    • 尝试过文本数据类型并遇到同样的问题。我猜 html/text 的处理方式相同。
    • 您如何在服务器端生成对metrics/getcontents2?name=Work/loc.txt 的响应,此网址返回什么http 标头?
    • 我用过@Produces("text/html") 和return response.status(200).entity("test").build();。有什么具体的我需要提供的吗?
    • 它是按预期返回 abc 只是 jQuery 说有一个错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 2016-01-07
    相关资源
    最近更新 更多