我试图用jQuery和JSON执行一些基本操作.目前,jQuery难以接受来自play framework应用程序的JSON响应.下面是仍然产生错误的代码的简化版本.

$.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'
});

始终触发错误回调.它会显示

Error... parsererror jQuery15001997238997904205_1298484897373 was not called

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()吗?

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

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

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".

Json相关问答推荐

替换字符串中特殊字符的Jolt变换

Jolt将键和值转换为单独的数组集

Terraform迭代JSON文件以获取键值对

创建Json嵌套文件 struct

使用 jq 重新格式化 JSON 输出

删除 JOLT 中的方括号

使用 jq 获取所有嵌套键和值

Vega-Lite规范:尽管在规范中提供了数据,但显示空图表

正向闪烁后的微调值

使用 JQ 获取 JSON 中的替代元素(输出:JSON 对象)

golang递归json来构造?

我如何将 JSON 格式与 flutter 一起使用?帮助使用 Gamebanana api

使用 jq 和 awk 拆分大型 JSON 文件

从 json 数组中仅提取一个值导致 vb6

Flutter:在本地文件 json 中搜索特殊的阿拉伯字符

将错误消息作为 JSON 对象发送

android - 在 adb logcat 输出中格式化 json 字符串

Golang struct 的 XML 和 JSON 标签?

雅虎财经全币种报价 API 文档

类型是接口或抽象类,不能实例化