8

How do I create a JSONP from an external JSON stream?

 2 years ago
source link: https://www.codesd.com/item/how-do-i-create-a-jsonp-from-an-external-json-stream.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How do I create a JSONP from an external JSON stream?

advertisements

I have two domains: www.domain1.com and www.domain2.com

I have a plain JSON feed on domain1.

I want to pull the JSON feed from domain1 and put it on a module on domain2.

From what I've read, the way to go about it is by using JSONP but how do you go about doing that? Is there a way to do it with just JQuery/javascript? Or would I have to use server-side code (I'm using Coldfusion). Also could I just use .getJSON and not .ajax (I'm a beginner so I've never used .ajax yet)

EDIT Okay I'm still getting confused. Just adding callback at the end of the url broke it. How could I make it so that instead of a remote path for a feed I am pulling an absolute path where this code is on www.domain2.com but the feed is on www.domain1.com?

var feed ="/event/json.tag/tag/sports/";

$.getJSON(feed,function(data) {

   $.each(data.items, function(i,obj) {

       do something here...
   }        

}


JSONP is just a callback function wrapped around a JSON object. General convention is to have an endpoint that returns JSON, unless a callback parameter is defined on the request, and returns JSONP in that case.

i.e. http://www.domain1.com/api/getStuff might return:

{'foo': 'bar', 'fizz': 'buzz'}

then http://www.domain1.com/api/getStuff?cb=cb123 should return:

cb123({'foo': 'bar', 'fizz': 'buzz'});

I don't know ColdFusion, but I assume this example is good: http://www.coldfusionjedi.com/index.cfm/2009/3/11/Writing-a-JSONP-service-in-ColdFusion

There's no client-only solution unless somebody else already built JSONP support into the server you're working with...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK