You need to add a callback parameter. I'll explain exactly why below.
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?
This is how your ajax response essentially looks like without the callback (e.g. http://cvrapi.dk/api?search=test&country=dk):
<script>
{"vat":11618405,"name":"TESTRUP ... (snip)
</script>
Of course there is a syntax error in this JavaScript! :)
Here is the ajax response with the callback (e.g. http://cvrapi.dk/api?search=test&country=dk&callback=callbackFunc):
<script>
callbackFunc({"vat":11618405,"name":"TESTR ... (snip)
</script>
Now that's valid JavaScript. The $.jsonp
with call callbackFunc()
in this example, and everything is right with the world.
The core elements of JSONP, or "JSON with padding", are as such:
- 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
- The response:
- Is just Javascript
- That consists of:
- A function call, the name of which you specified in the request
- The argument being the JSON data of interest
- Gets executed immediately, as if it were called from your own domain
This callback arrangement between you and the server, combined with
avoiding same-origin restrictions, is really the whole trick to JSONP
REF: So how does JSONP really work?, and Wikipedia: JSONP
Change your json code like this. Works like a charm. Notice the "callback" parameter added. JSONP expects this. Here is your edited JSFiddle: http://jsfiddle.net/Drakes/syng17fv/2/
REF: https://github.com/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')
}
});