我已经解决了这个问题,感谢所有评论和帮助过的人。解决方案在评论中。
我是Javascript,AJAX,Json的新手。
我有3个文件:
的index.html
<script src="example.js"></script>
<a href="#" id="get-data">Get JSON data</a>
<div id="show-data"></div>
example.js
$(document).ready(function () {
$('#get-data').click(function () {
var showData = $('#show-data');
$.getJSON('example.php', function (data) {
console.log(data);
var items = data.items.map(function (item) {
return item.key + ': ' + item.value;
});
showData.empty();
if (items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
showData.text('Loading the JSON file.');
});
});
和example.php
{
"items": [
{
"key": "First",
"value": 100
},{
"key": "Second",
"value": false
},{
"key": "Last",
"value": "Mixed"
}
],
"obj": {
"number": 1.2345e-6,
"enabled": true
},
"message": "Strings have to be in double-quotes."
}
在服务器/托管上,它正在运行并获取数据。 在本地主机上,在我的计算机上它不提取数据,它只是说&#34;加载JSON文件。&#34;。
在localhost上,index.html从服务器获取example.js,example.php也在与example.js相同的目录中的服务器上。
请帮助我理解为什么它不起作用,也许localhost应该已经安装了node.js?