There is even easier way how to work with JSONP using jQuery
<span class="pln">$</span><span class="pun">.</span><span class="pln">getJSON</span><span class="pun">(</span><span class="str">"http://example.com/something.json?callback=?"</span><span class="pun">,</span> <span class="kwd">function</span><span class="pun">(</span><span class="pln">result</span><span class="pun">){</span> <span class="com">//response data are now in the result variable</span><span class="pln"> alert</span><span class="pun">(</span><span class="pln">result</span><span class="pun">);</span> <span class="pun">});</span>
Using CORS
Cross-Origin Resource Sharing (CORS) is a W3C spec that allows cross-domain communication from the browser. By building on top of the XMLHttpRequest object, CORS allows developers to work with the same idioms as same-domain requests.
Javascript programming styles
My current state of thinking:
How to return the response from an asynchronous call?
I tried to return the value from the success callback as well as assigning the response to a local variable inside the function and return that one, but none of those ways actually return the response.
Synchronous
Imagine you make a phone call to a friend and ask him to look something up for you. Although it might take a while, you wait on the phone and stare into space, until your friend gives you the answer you needed.
Asynchronous
You call your friend again for the same reason. But this time you tell him that you are in a hurry and he should call you back on your mobile phone. You hang up, leave the house and do whatever you planned to do. Once your friend calls you back, you are dealing with the information he gave to you.
Solution(s)
Embrace the asynchronous nature of JavaScript! While certain asynchronous operations provide synchronous counterparts (so does “Ajax”), it’s generally discouraged to use them, especially in a browser context.