使用jQuery,从跨域URL访问json,其中json的格式可能不正确 [英] with jQuery, access json from cross domain url where json may be poorly formed
问题描述
我正在使用jQuery的ajax函数来访问跨域网址.网址将返回json.我正处于发现阶段,但是我认为,因为json值包含多个'&'字符串,所以json eval抛出错误并停止了我的客户端脚本的执行.我得到的错误是未终止的字符串文字".我知道,如果我将返回的json硬编码到本地div中,然后删除&";字符串(以及几个隐藏的特殊字符),我可以成功地将json转换为eval. 无论是通过变通方法,还是通过对我的代码进行更正,我该怎么做才能从URL中获取json并将其作为有效的json对象存储在我的客户端javascript中?
I'm using jQuery's ajax function to hit a cross domain url. The url will return json. I'm in the discovery phase with this but I think, because the json values contain several '"' strings, the json eval is throwing an error and stopping the execution of my client side script. The error that I get is "unterminated string literal". I know that if I hard-code the returned json by putting it in a local div and remove the '"' strings (and a couple of hidden special characters), I can get the json to eval successfully. Whether through work-around, or through a correction to my code, what can I do to get the json from the url and store it in my client side javascript as a valid json object?
我当前的代码.没有定义的函数(成功,完成,错误,dataFilter)执行:
my current code. none of the defined functions (success, complete, error, dataFilter) execute:
$(function() {
$.ajax({
url: "http://www.codemash.org/rest/sessions.json?format=jsonp&callback=?",
dataType: "jsonp",
success: successFunc,
complete: completeFunc,
error: errorFunc,
dataFilter: dataFilterFunc
});
});
function successFunc() { console.log('successFunc(). enter.'); }
function completeFunc() { console.log('complete(). enter.'); }
function errorFunc() { console.log('errorFunc(). enter.'); }
function dataFilterFunc(data, type) {
data.replace(/\W/g, ' ');
return data;
}
推荐答案
问题是JSONP服务,它完全消除了callback
参数.
The problem is the JSONP service, it is dismissing completely the callback
parameter.
JSONP 响应只是一个使用callback
get参数作为函数名称的函数调用:
A JSONP response is simply a function call using the callback
get parameter as the function name:
如果您查看某些JSONP服务的响应,应该是这样的:
If you look the response of some JSONP service, it should be like this:
http://somesite.com/jsonp?callback= myCallback
会返回:
myCallback({/*json*/});
您发布的正在返回 普通 有效 JSON,但不能将其作为 JSONP 处理响应.
While the one you post is returning plain valid JSON, but it cannot be handled as a JSONP response.
这篇关于使用jQuery,从跨域URL访问json,其中json的格式可能不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!