2013-10-22 56 views
0

我相信這是一個容易的,但我不知道如何做到這一點。我有一個PHP文件,它從MySQL數據庫讀取一些數據並以JSON格式返回數據。 現在我正在尋找一種方法將這些數據放入HTML中,以便將「data_from_json」替換爲「18.5」(在本例中)。 任何幫助表示讚賞。用JSON數據填充HTML

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]] 
+1

向我們顯示您的JSON數據。 – Andy

+1

閱讀本文[在html中顯示json](http://stackoverflow.com/questions/18283003/display-json-in-html) – super

回答

1

我假設你的HTML文件是不同的,你的PHP腳本文件不同的是,

你可以簡單地做一個Ajax請求到php腳本並消耗它的返回類型,然後在ajax請求的成功事件中,您可以設置所需的td的innerText 即ie你的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 Ajax請求或現代jQuery的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); 
      } 
     } 
    }); 
} 
+0

這個工程就像一個魅力。非常感謝你! – user2877744

0

可以嘗試<td align="right"> "<?php echo $data_from_json[0][0] ?>" </td>。更新你的php變量data_from_json$data_from_json

我是一個新的PHP傢伙。這只是一個建議。

+0

我認爲這在技術上會起作用,並不確定,但即使它在其他答案中的穩定性遠低於ajax方法,所以我不會推薦它。 – jhocking

+0

如果使用ajax。我同意在調用服務後使用'$('td')。eq(1).text(data)''。但我認爲問題是提問者想知道如何在他的PHP代碼中呈現。 – Sheldon

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 Javascript Ajax示例here