JSON 从 PHP 到 JavaScript

发布于 2024-11-16 18:44:47 字数 1052 浏览 0 评论 0原文

一个稍微不同的问题全部 其他...我可以使用以下命令轻松地将 JSON 从 PHP 页面传递到 JavaScript jQuery.ajax() 方法,但这是我的情况:

我在 MySQL 中有一组联系人数据,每个数据都有名字、姓氏、纬度、经纬度。我创建了一个页面,其中一半以表格格式显示联系人数据(名字、姓氏)。另一方面,我有一个 Google 地图,其中填充了数据集(纬度、经度)中的标记。现在,为了让两半共享相同的数据集,有两种方法,但我对这两种方法都不满意:

  1. 在 PHP 文件中,从 MySQL 中提取数据,将该数据集用于表,然后转换该数据转换为 JSON,将其写入 JavaScript 变量并使用该变量填充 Google 地图。不喜欢这样做,因为有数百个数据点,这意味着 JSON 字符串非常大并且使页面膨胀,并且源中的所有数据都以人类可读的形式存在(我知道无论如何数据都在那里)在所有情况下,它都在客户端,在这里更明显)。

  2. 在 PHP 文件中,从 MySQL 中提取数据,将该数据集用于表,然后在我的 JavaScript 中,通过 jQuery.ajax() 对另一个生成的 PHP 文件进行 AJAX 调用JSON 数据。讨厌这个,因为它会导致对同一数据源的两次调用。

我确信我在这里遗漏了一些明显的东西,有什么指示/帮助吗?

编辑:根据上面的选项 #1,我很清楚如何将 JSON 从 PHP 回显到 JavaScript...只是对这两种解决方案都不满意(即 JSON 在源中,或者 JSON 实际上是对数据源的第二次调用)。

A slightly different question that all the others out there... I am able to easily pass JSON from a PHP page to JavaScript using the jQuery.ajax() method, but here is my situation:

I have a set of contact data in MySQL, each with firstname, lastname, lat, lng. I have created a page that on one half displays the contact data (firstname, lastname) in tabular format. On the other half, I have a Google Map that is populated with markers from the data set (lat, lng). Now, to allow the two halves to share the same dataset, there are two methods but I am happy with neither:

  1. In the PHP file, pull the data from MySQL, use that data set for the table, then convert that data to JSON, write it out to a JavaScript variable and use that variable to populate the Google Map. Don't like doing this, as there are hundreds of data points, meaning the JSON string is very large and bloats the page, along with having all the data in human readable form in the source (I understand the data is there no matter what as in all cases it is on the client side, just more apparent here).

  2. In the PHP file, pull the data from MySQL, use that data set for the table, then in my JavaScript, make an AJAX call via jQuery.ajax() to another PHP file that generates the JSON data. Hate this as it results in two calls to the same datasource.

I am sure I am missing something obvious here, any pointers/help?

EDIT: Per option #1 above, I am well aware of how to echo out JSON from PHP to JavaScript... just unhappy with both solutions (i.e. JSON is in source, or JSON is effectively a second call to the data source).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

浪漫之都 2024-11-23 18:44:47

最好的选择是在 mysql 服务器上启用缓存并进行两个相同的调用:

http://www .petefreitag.com/item/390.cfm

如果没有 a) 对数据库进行两次调用或 b) 将结果存储在 .txt 文件(或类似文件)中,并且通过ajax检索它。

我想你可以做 b) 但它看起来有点草率,并且可能会比简单地进行 2 个数据库调用产生更多的开销。

Your best bet would be to enable caching on your mysql server and make two identical calls:

http://www.petefreitag.com/item/390.cfm

You can't really put data in two different places without a) making two calls to the database or b) storing the results in a .txt file (or similar) and retrieving it via ajax.

I suppose you could do b) but it seems a little sloppy and would probably create more overhead than simply making 2 DB calls.

萌无敌 2024-11-23 18:44:47

您的要求是自相矛盾的:

  • 您的数据在表中采用人类可读的形式,但您反对通过 JSON 发送它,因为它“采用人类可读的形式 [...]”

  • 该表包含所有 tds、trs、但你介意发送相同的数据通过 JSON(它可能会占用更少的空间)。

不过,如果您确实反对 JSON 并且不介意该表,则可以从表中提取数据(无论如何您都会发送)。相当愚蠢,但这里是:

<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
<table id='test'>
    <tr>
        <td>John</td><td>Smith</td>
        <td>354.3</td><td>52.5</td>
    </tr>
    <tr>
        <td>Adam</td><td>Dreger</td>
        <td>12.3</td><td>  52      </td>
    </tr>
    <tr>
        <td>Filip</td><td>Smith</td>
        <td>354.3</td><td>7.5</td>
    </tr>
</table>
<script>
    var data = $("#test tr").map(function(){
        return [$("td", this).map(function(){
            return this.innerHTML.match(/^\s*\d+(.\d+)?\s*$/)? 
                parseFloat(this.innerHTML) : this.innerHTML;
        }).toArray()]
    })
</script>

这是著名的视图控制器模型模式,其中控制器查询视图以收集用作模型的数据;-)

更好的想法(但你反对发送 JSON)将是使用 JSON 发送数据,并使用 Javascript 生成表格。这样,模型和视图之间仍然有清晰的分离。这并不是真正的宗教事物,但如果您决定向显示的数据添加一些范围,则您将不必解析它。

有大量合理的插件可以帮助您将数据转换为表格,但您可能会逃脱:(

<div id='another'>
 - - -
</div>
<script>
    // I assume that data is an array of arrays
    $('#another').html(
        [
        '<table border="1">',
        $(data).map(function(){
            return ['<tr>',
            $(this).map(function(){return "<td>" + this + "</td>"}).toArray().join("")
            ,'</tr>']
        }).toArray().join(""),
        '</table>'
        ].join("")
    );

</script>

注意:上面的两个片段可以链接起来并导致重复第一个表格:有趣!)

编辑:< /strong>

即使没有在表中显示的数据也可以放在那里(例如,在不可见的范围内),并且使用一些简单的编码(例如 rot13)(不包含在答案中,但广泛可用)使临时复制/粘贴无法访问。就像这样:

    <style>.secret {display: none}</style>

    <tr>
        <td>Adam</td><td>Dreger</td>
        <td>12.3</td><td>  52  </td>
            <td><span class='secret'>({frperg:"ovt bar"})</span></td>
    </tr>

在代码中:

<script>
    var data = $("#test tr").map(function(){
        return [$("td", this).map(function(){
            return this.innerHTML.match(/^\s*\d+(.\d+)?\s*$/)? 
                parseFloat(this.innerHTML) : this.innerHTML;
        }).toArray(), 

            eval($(".secret", this).html().rot13())]
    })
</script>

Your requirements are self-contradicting:

  • your data is in human-readable form in a table, yet you object to send it via JSON, because it's "in human-readable form [...]"

  • the table is a huge bloat with all the tds, trs, and yet you mind sending the same data over JSON (it would probably take LESS space).

Nevertheless, if you REALLY object to JSON and do not mind the table, you can extract the data from the table (that you send anyway). Rather silly, but here goes:

<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
<table id='test'>
    <tr>
        <td>John</td><td>Smith</td>
        <td>354.3</td><td>52.5</td>
    </tr>
    <tr>
        <td>Adam</td><td>Dreger</td>
        <td>12.3</td><td>  52      </td>
    </tr>
    <tr>
        <td>Filip</td><td>Smith</td>
        <td>354.3</td><td>7.5</td>
    </tr>
</table>
<script>
    var data = $("#test tr").map(function(){
        return [$("td", this).map(function(){
            return this.innerHTML.match(/^\s*\d+(.\d+)?\s*$/)? 
                parseFloat(this.innerHTML) : this.innerHTML;
        }).toArray()]
    })
</script>

This is the famous View Controller Model pattern, where the View is queried by the Controller to gather data to be used as a Model ;-)

A much better idea (but you are against sending JSON) would be to send the data with JSON, and generate the table with Javascript. This way you still have a clear separation between model and a view. It's not really a religious thing, but if you decide to, say, add some spans to the displayed data, you will not have to parse it.

Plenty of reasonable plugins out there will help you turn your data into table, but you might get away with:

<div id='another'>
 - - -
</div>
<script>
    // I assume that data is an array of arrays
    $('#another').html(
        [
        '<table border="1">',
        $(data).map(function(){
            return ['<tr>',
            $(this).map(function(){return "<td>" + this + "</td>"}).toArray().join("")
            ,'</tr>']
        }).toArray().join(""),
        '</table>'
        ].join("")
    );

</script>

(note: the two snippets above can be chained and result in duplicating of the first table: fun!)

EDIT:

Even data that is not displayed in the table could be put there (eg. in invisible spans) and made inaccessible for a casual copy/paster using some trivial encoding, like rot13 (not included in the answer, but widely available). Like so:

    <style>.secret {display: none}</style>

    <tr>
        <td>Adam</td><td>Dreger</td>
        <td>12.3</td><td>  52  </td>
            <td><span class='secret'>({frperg:"ovt bar"})</span></td>
    </tr>

And in the code:

<script>
    var data = $("#test tr").map(function(){
        return [$("td", this).map(function(){
            return this.innerHTML.match(/^\s*\d+(.\d+)?\s*$/)? 
                parseFloat(this.innerHTML) : this.innerHTML;
        }).toArray(), 

            eval($(".secret", this).html().rot13())]
    })
</script>
丑丑阿 2024-11-23 18:44:47

这取决于数据集有多大。如果它是一个很大的有效负载,您可能希望将其作为外部文件(即发出 ajax 请求)来获取,以便让浏览器缓存它。但是,在大多数情况下,请尽可能减少 HTTP 请求的数量。就我个人而言,我会选择将 json 嵌入到 HTML 中,除非压缩后的长度可能大于 20 kb。

It depends on how large the data set is. If it's a big payload, you might want to source it as an external file (i.e. make an ajax request) in order to have the browser cache it. However, in most cases, minimize the number of HTTP requests as much as possible. Personally I'd go with embedding the json into HTML unless it's maybe >20 kb zipped.

睫毛溺水了 2024-11-23 18:44:47

我会使用#2 的变体。是的,通过 AJAX 获取 JSON,因为这将使页面加载更快,也更灵活——也许在将来的某个时候,您会希望能够在没有表格的情况下显示地图,或者类似的东西。

但是添加一个 PHP 来包装对数据源的调用并由生成 HTML 的页面和生成 JSON 的页面。这将使缓存查询结果变得更加容易,并消除重复的代码。

I would use a variation of #2. Yes, fetch the JSON via AJAX, as that will make the page load faster and will also be more flexible -- perhaps at some point in the future you'll want to be able to display the map without the table, or some such.

But add a PHP class that wraps the call to the datasource and that is used by both the page that generates the HTML and the page that generates the JSON. This will make it easier to cache the results of the query, and will eliminate duplicate code.

梦与时光遇 2024-11-23 18:44:47

不错的选择我总是以 JSON 格式将数据传递给客户端,使用这个命令

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

就这么简单,打印输出并像客户端的任何其他 Javascript 对象一样遍历它;)

good choice I always pass data to the client in JSON, use this command

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

It's as easy as that, print the output and traverse it like any other Javascript object at the client side ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文