开发者

Javascript Widgets to grab external JSON/XML ... How?

开发者 https://www.devze.com 2023-02-16 05:53 出处:网络
I would like to build a little embeddable widget for webpages that will access an API the serves up XML or JSON (I can choose between those two formats). What I\'d like to do is have the user just sel

I would like to build a little embeddable widget for webpages that will access an API the serves up XML or JSON (I can choose between those two formats). What I'd like to do is have the user just select a block of code and paste it into the website, much like the Twitter Widgets

Due to cross-domain security issues I can't just do an ajax call to load those external data sets, so am I down to just using an iFrame? I'd prefer something with a bit more flexibility in the output so that users could change it via CSS.

Is there anything that can be done other than opening the cro开发者_运维百科ss-domain privileges on the host site?


Read about jsonp.

Generally, an oversimplified implementation, just to explain how it works would be:

on the client:

  var s = document.createElement("script");
  s.src = "http://yoursever.com/path/to/server/page?r=mySpecialCallback"
  document.body.appendChild(s);

  function mySpecialCallback(data){
      //do stuff with data that server returned 

  }

on the server, for example in aspx

  <%=Request["r"]%>({name: "Don-Joy", age: 34 } );

or in Php

  <?php $_GET['r']?>({name: "Don-Joy", age: 34 } );

The limitations:

1 - no post. only GET. data sent to the server is limited to what fits in a URL

2 - the response of the server is not pure JSON - it has to be wrapped in a callback function, that the client gives the server it's name - in this example - using the r query-string parameter.

Have Fun


JSONP is your friend. Just send back the data in a dynamically added linked script.

First, Data request is sent by the client to your server via something like:

var script = document.body.appendChild(document.createElement("script"));
script.type = "text/javascript";
script.src = "http://yourserver/yourhandler?parameters=values";

Then, request the data server-side on your machine. Return the response as JavaScript. Something like:

DataResponse({ /* data here */ });

That script is loaded into the script element created earlier. DataResponse() is called on the requesting client.

0

精彩评论

暂无评论...
验证码 换一张
取 消