[英]Ajax cant load php json
问题是, json文件未显示。 我正在使用Xampp作为本地服务器。
php文件:
$array = array(
array(
"title" => "Erster Eintrag",
"description" => "Description",
"link" => "http://",
"pubDate" => "02.07.2015"
),
array(
"title" => "Zweiter Eintrag",
"description" => "Description",
"link" => "http://",
"pubDate" => "02.07.2015"
)
);
echo json_encode($json);
html文件:
$ajax({
url:'localhost/uebung/staticfeed.php',
type:'POST',
data:'data',
dataType: 'json',
success: function(result){
$('#feeds').html(result[0]);
}
})
在PHP中使用json_encode
返回包含值的JSON表示形式的字符串。
使用$array
来json_encode
而不是$json
。
echo json_encode($array);
/// ^^^^^^^^^
JavaScript使用$ .ajax,然后使用完整URL。
$.ajax({
url:'http://localhost/uebung/staticfeed.php',
type:'POST',
data:'data',
dataType: 'json',
success: function(result){
$('#feeds').html(result[0]);
});
您还需要在php文件中对数组进行编码。
echo json_encode($array);
将$ajax
更改$ajax
$.ajax
,这将消除代码中的错误,其他一切正常
您在PHP答案中缺少JSON标头,jQuery可能会将您的响应解释为纯文本或HTML ...
另外,您正在回显$json
而您的数组是$array
。
尝试使用PHP:
header('Content-type: application/json');
$array = [["title" => "Erster Eintrag","description" => "Description","link" => "http://","pubDate" => "02.07.2015"],["title" => "Zweiter Eintrag","description" => "Description","link" => "http://","pubDate" => "02.07.2015"]];
echo json_encode($array);
这在您的HTML上:
$.ajax({type: "POST", url: "localhost/uebung/staticfeed.php", data:data, dataType: "json", timeout: 25000, success: function (result) {
$('#feeds').html('First array:' + result.[0].title + '<br />Seccond array:' + result.[1].title );
}});
您需要在[结果]内部的数组中选择值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.