我确信这很容易,但我不知道如何实现这一目标。我有一个PHP文件,它从MySQL数据库中读取一些数据并以JSON格式返回数据。 现在我正在寻找一种方法将这些数据放入HTML中,以便“data_from_json”替换为“18.5”(在本例中)。 任何帮助表示赞赏。
HTML:
<div class="container">
<div class="bs-example bs-example-type">
<table class="table">
<tbody>
<tr>
<td>Temperature</td>
<td align="right"> "data_from_json" </td>
</tr>
</tbody>
</table>
</div>
</div>
JSON内容:
[[18.5]]
答案 0 :(得分:1)
我假设你的html文件不同,你的php脚本文件不同,
你可以简单地向php脚本发出一个ajax请求并使用它的返回类型,然后在ajax请求的成功事件中,你可以设置所需的td innerText
即在你的html页面中,在body标签的末尾,你可以创建一个这样的脚本:
<script language="javascript" type="text/javascript">
//variables
var scriptToExecute="myDbReader.php";//php script
//any data that you might want to send to the php script.
var data ='anyData='+anyValue;
//call ajax function
makeAjaxRequest(scriptToExecute,data,callBack);
function callBack(data){
$('#td').html(data);
}
</script>
其中td是td的id,你想要设置文本和makeAjaxRequest是一个简单的函数,它通过传统的XHR或现代jQuery的ajax执行ajax请求,即
function makeAjaxRequest(url,data,_callBack,_failure){
$.ajax({
url:url,
datatype:"application/json",
type:'get',
data: data,
success:function(data){
_callBack(data);
},
error:function(jqXHR, textStatus, errorThrown){
if(!_failure){
console.log(errorThrown);
}
else
{
_failure(jqXHR,textStatus,errorThrown);
}
}
});
}
答案 1 :(得分:1)
您可以使用jQuery.Ajax来调用PHP页面并加载它返回的数据。
$.ajax({
url: 'data_to_load.php',
type: 'GET',
dataType: 'JSON',
contentType: 'application/json;charset=utf-8;',
success: function (data) {
//Use data.d to access the JSON object that is returned.
},
error: function (ajaxrequest) {
//Use ajaxrequest.responseText to access the error that is returned.
}
})
您还可以查看纯Javascript Ajax示例here。
答案 2 :(得分:0)
<td align="right"> "<?php echo $data_from_json[0][0] ?>" </td>
吗?将您的php变量data_from_json
更新为$data_from_json
。
我是一个新的php家伙。这只是一个建议。