简体   繁体   English

使用Ajax在表中显示PHP脚本中的数据

[英]Display data from php script in a table using ajax

I am looking to display data by running some query via php script and then using ajax to show it on an html page. 我希望通过php脚本运行一些查询来显示数据,然后使用ajax将其显示在html页面上。

I have a php script that echos the data from a sql query in json format. 我有一个PHP脚本,它以json格式回显来自sql查询的数据。 The output looks like this: 输出看起来像这样:

{"Username":"Server","RICS":12739,"Exclusive_RICS":0}{"Username":"eikon1","RICS":4,"Exclusive_RICS":0}{"Username":"balbla","RICS":552,"Exclusive_RICS":0}{"Username":"somename","RICS":221,"Exclusive_RICS":201}

I would like to display this data using an $.ajax call. 我想使用$ .ajax调用显示此数据。

I did some research and came up with this: 我做了一些研究,并提出了:

$(document).ready(function(){

$.ajax({

    url : 'query.php',
    type : 'POST',
    data : {
        //'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        window.alert(data.Username)
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

});

However, it's not working properly. 但是,它不能正常工作。 I just get this alert: 我刚收到以下警报:

在此处输入图片说明

I am new to js/ajax/php so excuse me if I missed something simple. 我是js / ajax / php的新手,所以如果我错过了一些简单的事情,请原谅。

Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

EDIT: 编辑:

php code:

    $sql = 'select * from table';

$retval = sqlsrv_query($conn,$sql);
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}


while( $row = sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) ) {
    echo json_encode($row);
}

sqlsrv_free_stmt($retval);
//echo "Fetched data successfully\n";
sqlsrv_close($conn);

EDIT 2: Managed to get the output of php in correct JSON format through this. 编辑2:设法通过此操作以正确的JSON格式获取php的输出。 Now just need to display this using ajax. 现在只需要使用ajax来显示它。

while( $row = sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) ) {
    $rows[] = $row;
}
echo json_encode($rows);

Looping through your SQL result set and echoing each row separately produces an invalid JSON format. 遍历SQL结果集并分别回显每一行会产生无效的JSON格式。 Instead you should json_decode the entire SQL result set. 相反,您应该json_decode整个SQL结果集。

Here's how you can update your PHP code so that it outputs the correct format: 您可以按照以下方法更新PHP代码,以输出正确的格式:

php code: php代码:

$sql = 'select * from table';

$retval = sqlsrv_query($conn,$sql);
if(! $retval ) {
  die('Could not get data: ' . mysql_error());
}

echo json_encode( sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) );

sqlsrv_free_stmt($retval);
//echo "Fetched data successfully\n";
sqlsrv_close($conn);

There may be one more step necessary in your AJAX success callback. AJAX success回调中可能还需要执行另一步。 You'll have to JSON.stringify the result because PHP will send it back as plain text: 您将需要JSON.stringify结果,因为PHP会将其作为纯文本发送回:

success : function(data) {              
    var result = JSON.stringify( data );
    window.alert(result.Username)
}, 

Thanks for the help everyone. 感谢大家的帮助。 I was eventually able to figure out the issue. 我最终能够找出问题所在。

  • First of all, as pointed by users, my json format was not right. 首先,正如用户指出的那样,我的json格式不正确。 I fixed that with the solution in my edit. 我通过编辑中的解决方案解决了该问题。
  • Secondly, I had to reference my php directly with the exact address. 其次,我必须直接用正确的地址引用我的php。 I think it has to do with running queries from same server. 我认为这与从同一服务器运行查询有关。 Not sure perfectly. 不能完全确定。
  • Thirdly, i tried a plain ajax call and even that was failing. 第三,我尝试了一个普通的ajax调用,即使失败了。 It turns out my browser (chrome) needed a clean up. 原来我的浏览器(chrome)需要清理。 I cleared my cookies and it started to work fine. 我清除了cookie,它开始工作正常。 Why it was acting weird? 为什么表现奇怪? I have no idea! 我不知道!
  • Finally, now I needed to display the data in a table format and update the table frequently. 最后,现在我需要以表格式显示数据并经常更新表。 I am still working with that but this is what I got going for me right now: 我仍在与之合作,但这就是我现在想要的:

     $(document).ready(function() { (function poll() { $.ajax({ url : 'http://localhost/scripts/query.php', type : 'POST', data : {}, dataType:'json', success : function(response) { var json_obj = $.parseJSON(JSON.stringify(response)); var output=""; for (var i in json_obj) { output+="<tr>"; output+="<td>" + json_obj[i].time.date + "</td>" + "<td>" + json_obj[i].username + "</td>" + "<td>" + json_obj[i].rics + "</td>" + "<td>" + json_obj[i].exclusive_rics +"</td>"; output+="</tr>"; } $('#table_content').html(output); }, error : function(request,error) { alert("Request: "+JSON.stringify(request)); } , dataType: "json", complete: setTimeout(function() {poll()}, 5000), timeout: 2000 }) })(); 

    }); });

I really don't understand why this was so hard to do. 我真的不明白为什么这么难做到。 I am sure this is a common scenario and I really wish there was a more straightforward way of doing this. 我确信这是一个常见的情况,并且我真的希望有一种更直接的方法。 Hopefully, my final code will avoid others from wasting so much of their time. 希望我的最终代码可以避免其他人浪费大量时间。 Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM