Google会像这样返回
Unparsable Cuft to the json response:
throw 1; <dont be evil> { foo: bar}
>我当前的Web应用程序使用jQuery.Ajax来检索JSON数据.如何修改它们以使用有效数据?
解决方法
您应该从响应中删除开头部分:
$.ajax(url,{ dataType: "jsonp text",success: function(data) { var jsonString = data.replace(/^throw 1; <dont be evil> /,""); var responSEObject = $.parseJSON(jsonString); // do something with responSEObject ... } }
更新:
要在每个Ajax调用中重写,您还可以在jQuery中注册一个全局Ajax转换器:
$.ajaxSetup({ converters: { "text cleanedjson": function(data) { var jsonString = data.replace(/^throw 1; <dont be evil> /,""); return $.parseJSON(jsonString); } } }); $.ajax(url,{ dataType: "jsonp cleanedjson",success: function(responSEObject) { // do something with responSEObject ... } });
您仍需要在请求选项中指定已定义的dataType.
更新2:
如果你需要调整现有的调用来自动进行响应清理,你可以修补jQuery的ajax实现,以便在某些情况下自动使用你的转换器:
// store reference to original implementation $._ajax_original = $.ajax; // redefine jQuery's ajax function $.ajax = function(url,settings) { if (… your test for applicability here (e.g. an url check) …) { settings.dataType = "jsonp cleanedjson"; } return $._ajax_original(url,settings); };
请注意,在加载jQuery之后和第一次Ajax调用之前,必须包含此重新定义.您可能还需要考虑$.ajax也可以be called without a separate url
parameter ……
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。