【问题标题】:jQuery parser error ajax calljQuery解析器错误ajax调用
【发布时间】:2013-07-30 18:06:05
【问题描述】:

我正在尝试 .ajax 访问返回对象列表的 URL,我在 spring 中使用 jacksonJsonView 以在浏览器中返回 json。但是当我尝试这段代码时,它永远不会成功,但错误警报显示 textstatus 为“parseerror”。警报如下所示:'status=parsererror,error=jQuery15109695890768120119_1357924928198 was not called'

$(function() {  
$("#tags").autocomplete({
source: function( request, response ) {
    $.ajax({
        url: 'http://localhost:8181/jquery/api/states/regex?stateName='+request.term,
        method: 'GET',
        dataType: 'jsonp',
        success: function(json) {
        alert("test");

        },
        error: function(httpRequest, textStatus, errorThrown) { 
        alert("status=" + textStatus + ",error=" + errorThrown);
        }
    });
}
})

API 返回如下内容:

[

    {
        "id": 12,
        "stateName": "Vermont",
        "intPtLon": -72.673354,
        "intPtLat": 44.0605475,
        "stUsps": "VT"
    },
    {
        "id": 20,
        "stateName": "Virginia",
        "intPtLon": -78.6681938,
        "intPtLat": 37.5222512,
        "stUsps": "VA"
    }

]

添加以下行解决了这个问题,它在 IE 中运行良好,而在 firefox 中则没有那么多

【问题讨论】:

  • 您确定需要 JSONP 吗?
  • 如果我删除它,它会给出“status=error,error="
  • 看我的回答。假设将 dataType: 'jsonp', 更改为 dataType: 'json', 就足够了。

标签: jquery ajax spring


【解决方案1】:

你应该改变

dataType: 'jsonp',

简单

dataType: 'json',

或者,如果你真的需要 JSONP 并且不能使用 JSON - 你应该从服务器端的请求中获取回调参数并像这样包装响应:

请求["回调"] + "(" + string_with_json_response + ")";

所以,在结果中你会得到类似的结果:

jQuery15109695890768120119_1357924928198('{"response":"val"}');

【讨论】:

  • 将 jsonp 更改为 json 会给我“状态=错误,错误=”。我在哪里添加 Request["callback"] + "(" + string_with_json_response + ")"; ?
  • 嗯。这很奇怪。您在问题中显示的响应看起来像有效的 JSON。查看浏览器中开发人员工具的网络选项卡。你应该在它执行后在那里找到你的 ajax 请求并从那里得到响应。您提供的回复看起来没问题,它应该可以与dataType":'json' 一起正常工作。关于在哪里添加 - 我只能给出方向。它应该与返回当前响应的位置相同。不知道你是如何在 Java 中做到这一点的。
  • firebug/net 中一切正常,响应头看起来像这样 Content-Type application/json Server Jetty(6.1.22) Transfer-Encoding chunked
  • json 周围的 [] 重要吗?不知道如何删除它。在一些帖子中,他们认为这可能是问题
  • 嗯。这根本不应该是一个问题。这是一个有效的 JSON 数组。您是否检查过纯响应文本?可能你有一些你看不到的垃圾,但它破坏了 jQuery
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
  • 2012-05-14
  • 2012-10-13
相关资源
最近更新 更多