簡體   English   中英

無法通過jQuery訪問AJAX響應數據

[英]Unable to access AJAX Response Data through jQuery

我已經搜索並嘗試了幾個小時,但未成功。

我有一個現有頁面,該頁面在HTML表中顯示使用PHP的數據庫中的簡單數據。 現在,我要實現AJAX功能,以便無需刷新頁面即可刷新數據。

我已經實現了此解決方案 ,據我了解,AJAX調用部分正在運行,並且值已按預期刷新。 但我一直堅持獲取價值。

index.php(主頁)

<html>
<head>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
</script>
</head>
<body>
<h3>Output: </h3>

<table border="1" id="output"></table>

<script id="source" language="javascript" type="text/javascript">
$(function() {
    update_content();
});

    function update_content() 
    {
    $.ajax({                                      
      url: 'query.php',                  //the script to call to get data          
      data: "",                        //you can insert url argumnets here to pass to query.php
      dataType: 'json',                //data format      
      success: function(data)          //on recieve of reply
      {
        if(data){       
       (data + '').length;
    }
    var temp = new Array();
        $('#output').html("<tr><td>"+data["symbol"]+"</td></tr>");
      } 
    });
    setTimeout(function(){
            update_content();
        }, 1000);
    }
</script>
</body>
</html>

query.php(用於AJAX調用)

<?php 
include('inc/connection.php');

# Main query
$sql = "
select LastUpdated, symbol, sum
from TheTable
";

$result = mysql_query($sql);

while($row = mysql_fetch_row($result)){
$table_data[]=array("LastUpdated"=>$row[0],"symbol"=>$row[1],"sum"=>$row[2]);
}
echo json_encode($table_data);
?>

如果我直接在瀏覽器中運行query.php,則會看到此格式的所有數據: [{"LastUpdated":"20170614","symbol":"AUD","sum":"20"},{"LastUpdated":"20170614","symbol":"AUD","sum":"10"}]

但是在我的主頁上,我看到表內undefined 理想情況下,我希望具有所有值(可以在上面的代碼中使用JS循環)來顯示從DB提取的所有記錄(可變記錄數)。

提示/修改
當我改變時:
$('#output').html("<tr><td>"+data["symbol"]+"</td></tr>");

$('#output').html("<tr><td>"+data[0]+"</td></tr>");
在index.php中



$table_data[]=array("LastUpdated"=>$row[0],"symbol"=>$row[1],"sum"=>$row[2]);

$table_data[]=$row;
在query.php中,

然后我只獲得第一行作為字符串,如20170614,AUD,40
結束提示/修改

很抱歉,這是一個愚蠢的問題。 我是jQuery的新手,也是第一次嘗試AJAX。

PS我知道mysql_ *函數已被棄用,並且我知道該漏洞。

您的幫助將不勝感激。

更新數據表時,您可能只想重建表。 在回調函數中,您需要遍歷數組並將新行添加到表中。

$.ajax({
  url: 'query.php', //the script to call to get data          
  dataType: 'json', //data format      
  success: function(data) {
      if (!Array.isArray(data) || !data.length) {
          return;
      }

      $("#output").empty(); //clear old table data
      for(var i = 0, len = data.length; i < len; i++) {

        $("#output").append(
          "<tr><td>" + data[i].LastUpdated + "</td>" + 
          "<td>" + data[i].symbol + "</td></tr>" +
          "<td>" + data[i].sum + "</td></tr>"
        );
      }
    }
});

您必須按如下所述更改代碼。

data["symbol"]

data.symbol

讓我知道是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM