Javascript Cross domain JSON -


hi trying use javascript , html read json object url. using following code:

function getjsonp(url, success) {      var ud = '_' + +new date,         script = document.createelement('script'),         head = document.getelementsbytagname('head')[0]             || document.documentelement;      window[ud] = function(data) {         head.removechild(script);         success && success(data);     };      script.src = url.replace('callback=?', 'callback=' + ud);     head.appendchild(script); }  getjsonp('http://weburl?&callback=?', function(data){     console.log(data); }); 

as have guessed getting not @ same origin document, , parent of track element not have 'crossorigin' attribute. origin 'null' therefore not allowed access.

fyi server returns json data , doesnot have callback function.

cheers help.

the server either needs have cors enabled using headers this: (credits answer here: cors php headers)

// allow origin if (isset($_server['http_origin'])) {     header("access-control-allow-origin: {$_server['http_origin']}");     header('access-control-allow-credentials: true');     header('access-control-max-age: 86400');    // cache 1 day }  // access-control headers received during options requests if ($_server['request_method'] == 'options') {      if (isset($_server['http_access_control_request_method']))         header("access-control-allow-methods: get, post, options");               if (isset($_server['http_access_control_request_headers']))         header("access-control-allow-headers: {$_server['http_access_control_request_headers']}");      exit(0); } 

or server needs output jsonp like:

echo $_get['callback'] . '(' . json_encode($whatever) . ')'; 

another option if not on own server create php file on own server filegetcontents on url need read (with json data without cors) , echo same data in jsonp format. can use new php file (url) in pure javascript getjson function.

without server in middle or cors or jsonp, not possible.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -