0

我确信这很容易,但我只是不知道如何做到这一点。我有一个 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]]
4

3 回答 3

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 示例。

于 2013-10-22T13:06:17.893 回答
1

我假设您的 html 文件不同并且您的 php 脚本文件不同,

您可以简单地向php脚本发出ajax请求并使用其返回类型,然后在ajax请求的成功事件中,您可以innerText 在html页面中设置所需的td ie,在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);
          }
       }
    });
}
于 2013-10-22T13:04:47.810 回答
0

你能试试吗<td align="right"> "<?php echo $data_from_json[0][0] ?>" </td>?将您的 php 变量更新data_from_json$data_from_json.

我是一个新的 php 家伙。这只是一个建议。

于 2013-10-22T13:05:52.893 回答