为什么会返回语法错误?
Why does this return a syntax error?
http: //jsfiddle/syng17fv/
jquery.jsonp github/jaubourg/jquery-jsonp
jquery.jsonp github/jaubourg/jquery-jsonp
回复 cvrapi.dk/api?search=test&country=dk
$.jsonp({ url : 'cvrapi.dk/api?search=test&country=dk', success : function(json){ console.log('success') }, error : function(){ console.log('err') } });更新
此作品
update
This works
$.ajax({ type : 'GET', dataType : 'jsonp', url : '//cvrapi.dk/api?search=test&country=dk', success : function(res){ } });推荐答案
您需要添加一个回调参数。我将在下面解释原因。
You need to add a callback parameter. I'll explain exactly why below.
如果没有回调,JSONP调用将无效。数据加载到脚本标记中,如果代码不是方法调用的形式,结果将只是一个被丢弃的对象,并且永远不会调用成功回调方法。
A JSONP call doesn't work without a callback. The data is loaded in a script tag, and if the code is not in a form of a method call, the result would just be an object that was discarded, and the success callback method would never be called.
为什么[不使用回调]会返回语法错误?
Why does [not using a callback] return a syntax error?
这就是你的ajax响应在没有回调的情况下基本上是这样的(例如 http:// cvrapi .dk / api?search = test& country = dk ):
This is how your ajax response essentially looks like without the callback (e.g. cvrapi.dk/api?search=test&country=dk):
<script> {"vat":11618405,"name":"TESTRUP ... (snip) </script>当然这个JavaScript中存在语法错误!:)
Of course there is a syntax error in this JavaScript! :)
这是带回调的ajax响应(例如 cvrapi.dk/api?search=test&country=dk& callback = callbackFunc ):
Here is the ajax response with the callback (e.g. cvrapi.dk/api?search=test&country=dk&callback=callbackFunc):
<script> callbackFunc({"vat":11618405,"name":"TESTR ... (snip) </script>现在这是有效的JavaScript。 $ .jsonp 在这个例子中调用 callbackFunc(),一切都是正确的世界。
Now that's valid JavaScript. The $.jsonp with call callbackFunc() in this example, and everything is right with the world.
JSONP的核心元素,或带填充的JSON,如下:
The core elements of JSONP, or "JSON with padding", are as such:
- 包含一个特殊的p aram 提供回调函数的名称
- A callback function defined on your site.
- A request to the remote API via tag
- Includes a special param providing the name of your callback function
- 只是Javascript
- 包括:
- Is just Javascript
- That consists of:
- 函数调用,您在请求中指定的名称
- 参数是感兴趣的JSON数据
- 立即执行,就好像是从你的自己的域名
此回调你和服务器之间的安排,结合避免同源限制,实际上是JSONP的全部技巧
This callback arrangement between you and the server, combined with avoiding same-origin restrictions, is really the whole trick to JSONP
REF:那么JSONP如何运作?和维基百科:JSONP
像这样更改你的json代码。奇迹般有效。注意添加了callback参数。 JSONP期待这一点。这是您编辑过的JSFiddle: jsfiddle/Drakes/syng17fv/2/
Change your json code like this. Works like a charm. Notice the "callback" parameter added. JSONP expects this. Here is your edited JSFiddle: jsfiddle/Drakes/syng17fv/2/
REF: github/jaubourg/jquery-jsonp/blob/master/doc/TipsAndTricks.md
$.jsonp({ url : '//cvrapi.dk/api?search=test&country=dk&callback=?', success : function(json){ console.log('success') }, error : function(){ console.log('err') } });更多推荐
即使响应是json,jquery + jsonp也会返回语法错误
发布评论