[英]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. 我试图从托管在我的Web主机上的PHP脚本获取JSON数据(在Xampp中本地)。
The PHP script is like this: PHP脚本如下所示:
<?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: 从服务器直接运行( http://website.com/php/script.php )时显示的数据:
{
"id": "1",
"url": "http://twitter.com",
"text": "test 001"
}
And the broken HTML / JS which should output this: 以及破碎的HTML / JS应该输出以下内容:
<!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. 我在xampp中将HTML作为.php脚本运行,我不确定这是否与jQuery或常规JS有任何区别,但大多数情况似乎都很好。
How can i get back the data "1", " http://twitter.com " and "test 001" etc? 如何获取数据“ 1”,“ http://twitter.com ”和“ test 001”等?
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. 在这种情况下的问题是我在xampp中将HTML作为.php文件运行,由于某种原因,该文件不返回任何数据。
After changing it to .html instead it then ran fine. 将其更改为.html后,它可以正常运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.