jQuery JSON响应始终触发ParseError [英] jQuery JSON response always triggers a ParseError

查看:79
本文介绍了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皮棉工具也都可以验证.将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可以将dataType从在Content-Type标头中接收到的dataType转换为您所需要的.例如,如果您希望将文本响应视为XML,请使用文本xml"(用于dataType).也许您可以尝试文本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天全站免登陆