jQuery JSON 响应总是触发 ParseError [英] jQuery JSON response always triggers a ParseError

查看:20
本文介绍了jQuery JSON 响应总是触发 ParseError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 jQuery 和 JSON 执行一些基本操作.目前 jQuery 难以接受来自我的播放框架应用程序的 JSON 响应.下面是仍然产生错误的代码的简化版本.

I am trying to preform some basic operations with jQuery and JSON. Presently having difficulty with jQuery accepting JSON response from my play framework application. Below is a simplified version of the code that still produces the error.

$.ajax({
    type: 'POST',
    url: "@{FrontEnd.isUsernameAvailable()}",
    data: "name=thisnameisavailable",
    cache: false,
    success: function(data) {
        console.log("Success... ");
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log("Error... " + textStatus + "        " + errorThrown);
    },
    dataType: 'json'
});

错误回调总是被触发.它显示

The error callback is always triggered. It displays

错误... parsererror jQuery15001997238997904205_1298484897373 没有被调用

Error... parsererror jQuery15001997238997904205_1298484897373 was not called

通过 Firebug 检查返回的 JSON 没有显示任何错误,并且各种 JSON lint 工具也进行了验证.将 dataType 更改为text"会调用成功.但我试图将 isUsernameAvailable 调用用作 jQuery 验证插件的一部分,因此我需要它返回有效的 JSON.

Inspecting the returned JSON through Firebug shows no errors and various JSON lint tools also validate. Changing dataType to "text" makes success be called. But I am trying to use the isUsernameAvailable call as part of jQuery validation plugin so I need it to return valid JSON.

推荐答案

也许我误解了,但你不能将 dataType 设置为 text 和 JSON.parse() 返回的数据?

Maybe I'm misunderstanding, but couldn't you set the dataType to text and JSON.parse() the returned data?

success: function(data) {
    data = JSON.parse(data);
    // process data
},

编辑添加普遍同意的解决方案(以前仅评论):

Edited to add generally agreed upon solution (previously a comment only):

我刚刚查看了 api.jquery.com/jQuery.ajax,它看起来像使用 jQuery 1.5可以进行各种类型的转换.多个空格分隔的值:从 jQuery 1.5 开始,jQuery 可以将数据类型从它在 Content-Type 标头中收到的内容转换为您需要的内容.例如,如果您希望将文本响应视为 XML,请使用文本 xml" 用于数据类型."也许你可以试试文本 json".

I just took a look at api.jquery.com/jQuery.ajax and it looks like with jQuery 1.5 you can do a type conversion of sorts. "multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType." Maybe you can try "text json".

这篇关于jQuery JSON 响应总是触发 ParseError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆