简体   繁体   中英

How to get JSON data from hosted PHP script using Javascript?

I am trying to get JSON data (Locally in Xampp) from a PHP script hosted on my web host.

The PHP script is like this:

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST'); 

// Creating the data array
$data = array(
    'id' => '1',
    'url' => 'http://twitter.com',
    'text' => 'test 001',
);

header('Content-Type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

?>

The data it displays when run directly ( http://website.com/php/script.php ) from the server:

{
    "id": "1",
    "url": "http://twitter.com",
    "text": "test 001"
}

And the broken HTML / JS which should output this:

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>

$.getJSON('http://website.com/php/script.php', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

</script>

</head>

<body>

<span id="output"></span>

</body>
</html>

I run the html as a .php script in xampp, i am not sure if that makes any difference with jQuery or regular JS but most things seem fine.

How can i get back the data "1", " http://twitter.com " and "test 001" etc?

The problem in this case was that i was running the html as a .php file in xampp which for some reason caused it to not return any data.

After changing it to .html instead it then ran fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM