通过PHP和jQuery将MySQL解析为JavaScript数组 [英] Parsing MySQL into JavaScript Arrays through PHP and jQuery

查看:57
本文介绍了通过PHP和jQuery将MySQL解析为JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

终极目标:我想将我保留在MySQL数据库中的数据放入JavaScript中的数组数组中,因此可以在客户端进行操作。

到目前为止,我已经能够使用以下代码从我的数据库中提取数据:

So far, I have been able to pull data from my database with this code:

<?php
...
$num=1;

$q = "SELECT blah1, blah2, blah3 WHERE blah4=$num";

$sth = mysqli_query ($database, $q);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
    }

print json_encode($rows);

?>

(来自: JSON编码MySQL结果

这是我被困的地方,因为我无法将这些数据导入JavaScript。

This is where I am stuck, because I am having trouble getting this data into JavaScript.

我能找到的一个解决方案是在Javascript中解析单独的PHP数组

One solution I can find is Parsing a Separate PHP Array in Javascript:

<script>
     var jsonarray = <?php echo json_encode($array); ?>;
     // now you can use jsonarray in your javascript
</script>

但是这个实现的问题是它会吐出我查询到的所有数据库内容页面的源代码。如果我必须这样做,我不妨跳过数据库并将所有内容保存在javascript中。

But the problem with this implementation is that it would spit out all of the database content I query onto the source-code of the page. If I have to do this, I might as well skip the database and just keep all of the content in javascript.

我在想jQuery /必须有办法AJAX将$ num的值传递给PHP脚本,获取此数据并将其放入JavaScript数组中,而无需将所有数据输出到页面。

I am thinking there must be a way with jQuery/AJAX to pass the value of $num to a PHP script, grab this data and put it into a JavaScript Array without having to output all of it to the page.

任意我将不胜感激。

谢谢!

推荐答案

此解决方案你发布了:

<script>
  var jsonarray = <?php echo json_encode($array); ?>;
  // now you can use jsonarray in your javascript
</script>

实际上是一种非常好的方法。使用AJAX的速度非常慢(因为网络延迟)。

Is actually a very good approach. Using AJAX is drastically slower (because of network latency).

除非你因某些原因确实需要AJAX,否则你应该避免使用它。它会为页面添加明显的加载时间,通常没有任何好处。

Unless you really need AJAX for some reason, you should avoid using it. It will add a noticeable split second of load time to the page, often for no benefit at all.

最重要的是在构建页面时,你想尝试减少浏览器和服务器之间的单个网络请求数。请求越少,页面越快。对于javascript和ajax尤其如此,因为它们是不可预测的,并且浏览器发现很难优化页面的任何部分使用它。

Above all when structuring your page, you want to try and reduce the number of individual network requests between the browser and the server. The less requests the faster your page will be. This is especially true for javascript and ajax, because they are unpredictable and browsers find it very difficult to optimise any part of the page where it's being used.

我们正在谈论大约四分之一秒与一百万分之一秒相比,完全相同的最终结果。

We're talking about one quarter of a second compared to one millionth of a second, for exactly the same end result.

这篇关于通过PHP和jQuery将MySQL解析为JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆