打开“http://localhost/uebung/index.html”时仅显示 HTML/CSS(无法读取 JSON)
JSON 数据(目前有效):
<?php
$array = array(
array(
"title" => "Erster Eintrag",
"description" => "Hier kommt eine Beschreibung hin!",
"link" => "http://",
"pubDate" => "02.07.2015"
),
array(
"title" => "Zweiter Eintrag",
"description" => "Hier kommt eine Beschreibung hin!",
"link" => "http://",
"pubDate" => "02.07.2015"
)
);
echo json_encode($array);?>
html文件(此文件无法读取json文件):
<script type="text/javascript">
$.ajax({
url:'http://localhost/uebung/staticfeed.php',
type:'POST',
data: val,
dataType: 'json',
success: function(data){
$.each(data, function(key, val){
$('#feeds').append('<div id="' + key + '">' + val.title + ' ' + val.description + ' ' + val.link + ' ' + val.pubDate + '</div>');
});
}
})
</script>
<div id="feeds">dsf
</div>
最佳答案
这样写可以告诉你的脚本你正在发送 JSON
header("Content-Type: application/json", true);
echo json_encode($array);?>
或
在迭代之前解码 JSON。
success: function(data){
data = $.parseJSON(data);
$.each(data, function(key, val){
....
关于javascript - 无法使用 Ajax 读取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31188295/