我有以下问题。我有一个 PHP 文件,它应该给我一个 JSON 对象,以便我可以在我的 HTML 文件中显示它。这非常有效,我收到了一个看起来像 JSON 对象的输出,但尽管我将在此处发布 PHP 文件:
<?php
header('Content-Type: application/json');
$erg = array (
"London" => array(
"Wetter" => "Regnerisch",
"Grad" => 12
),
"Manchester" => array(
"Wetter" =>"Sonnig",
"Grad" => 15
),
"Cambridge" => array(
"Wetter" => "Bewoelkt",
"Grad" => 5
)
);
echo json_encode($erg, JSON_PRETTY_PRINT);
?>
我读过一些关于 $.ajax 的内容,但我不知道我是否可以像这样使用它:
$(document).ready(function() {
var newHtml;
$.ajax({
url: 'Server2.php',
type: 'get',
cache:false,
success: function(json) {
$.each(json,function(i, item) {
newHtml += '<div>' + item.Wetter + '</div>'
})
$('#inhalt').html(newHtml);
}
});
});
但是当我尝试在浏览器中显示它时,我收到以下错误:
所以我只想在一个 div 中显示 PHP 文件的输出,我将其插入到我的 div 中,并在我的 HTML 文档中插入了 id inhalt。
非常感谢你们的帮助。
最佳答案
刚刚测试了这段代码。为 jQuery 部分尝试此代码:
$(document).ready(function() {
var newHtml;
$.ajax({
type: 'GET',
dataType: 'json',
url: 'Server2.php',
complete: function( json ){
//$.each( json.responseJSON, function(i, item) {
// newHtml += '<div>' + item.Wetter + '</div>'
//});
// Try this for the keys
for(var key in json.responseJSON) {
newHtml += '<div>' + key + '</div>'
}
$( '#inhalt' ).html( newHtml );
}
});
});
更多信息
如果你想获得每个位置的 key 和 Wetter
key ,那么试试这个
for(var key in json.responseJSON ) {
var wetter = json.responseJSON[ key ].Wetter,
grad = json.responseJSON[ key ].Grad;
// You can now use the wetter and grad vars wherever you want inside this function
newHtml += '<div>' + key + '</div>'
}
关于javascript - 在 javascript 中使用 PHP 文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34837153/