1

How can I get JSON data from this URL, access the "url" field and store it as a string. All solutions out there seem to only work on a server. i.e. running php on an apache server or something like that. When I run my code:

$(document).ready( function() { 
    var url = 'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US';
    $.get(url, function (data) {
        $(data).find("url").each(function () { 
            var el = $(this);

        console.log("------------------------");
        console.log("link      : " + el.find("url").text());
        });
    });
});

I get the error: XMLHttpRequest cannot load ... No 'Access-Control-Allow-Origin' header is present on the requested resource. Which I've research extensively but all the solutions don't work for local files. Both JSONP and CORS don't seem to work here.

EDIT: Let me try to refine this to a simpler question. Is it possible to parse a JSON object without using server-side scripting?

Probably
  • 426
  • 5
  • 19
  • 4
    You can't access it on any other domain than bing.com – Daniel Lizik Jul 06 '16 at 19:36
  • 1
    Bing's not operating a charity. – miyamoto Jul 06 '16 at 19:37
  • @Daniel_L I've seen the code `document.domain = 'example.com'` to set the domain, can this be used locally or only on a server? – Probably Jul 06 '16 at 19:43
  • this wouldn't solve your issue.. but just letting you know for if the url contains a JSON object, you could use `$.getJSON` instead of `$.get` – Neville Nazerane Jul 06 '16 at 19:47
  • @NevilleNazerane `$.getJSON` will still result in the same error. – Probably Jul 06 '16 at 19:50
  • No, this is not possible. Not unless you build your own browser in a desktop app of sorts or resort to one of the other methods that involve server-side code. (note that said server-side code doesn't necessarily need to be on *your* server) – Kevin B Jul 06 '16 at 20:14
  • @j76 yep.... as i mentioned it wouldn't resolve your issue... it is just a suggestion when you use ajax for json data – Neville Nazerane Jul 06 '16 at 20:43

1 Answers1

-3

If that's suitable for you to use server-side scripting, try this one. Javascript to set post query

$(document).ready( function() {
    var url = 'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US';
    $.post('/get.php',{u:url}, function (data) {        
        console.log(data);
    });
});

Server file get.php:

$ch = curl_init($_POST['u']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
Vyacheslav
  • 157
  • 4
  • The goal here is to not use php. There are loads of solutions for this if the page is php, but I don't have access to a server where this page is. – Probably Jul 06 '16 at 20:05