简体   繁体   English

JSON从PHP到JavaScript

[英]JSON from PHP to JavaScript

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: 这稍微不同的问题所有 在那里......我能够很容易地从一个PHP页面使用JSON传递到JavaScript的jQuery.ajax()方法,但这里是我的情况:

I have a set of contact data in MySQL, each with firstname, lastname, lat, lng. 我在MySQL中有一组联系数据,每个联系数据都包含名字,姓氏,纬度,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). 在另一半上,我有一个Google Map,其中填充了数据集中的标记(纬度,经度)。 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. 在PHP文件中,从MySQL中提取数据,使用该表的数据集,然后将其转换为JSON,将其写到JavaScript变量中,然后使用该变量填充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). 不喜欢这样做,因为有数百个数据点,这意味着JSON字符串非常大,使页面page肿,同时所有数据都以人类可读的形式包含在源中(我明白无论什么数据都存在就像在所有情况下一样,它都是在客户端,在这里更明显)。

  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. 在PHP文件中,从MySQL中提取数据,为该表使用该数据集,然后在我的JavaScript中,通过jQuery.ajax()对另一个生成JSON数据的PHP文件进行AJAX调用。 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 (ie JSON is in source, or JSON is effectively a second call to the data source). 编辑:根据上面的选项#1,我很清楚如何从PHP向JavaScript回显JSON ...只是对两种解决方案都不满意(即JSON在源中,或者JSON实际上是对数据源的第二次调用)。

Your best bet would be to enable caching on your mysql server and make two identical calls: 最好的选择是在mysql服务器上启用缓存并进行两个相同的调用:

http://www.petefreitag.com/item/390.cfm 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. 没有a)两次调用数据库,或b)将结果存储在.txt文件(或类似文件)中并通过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. 我想您可以做b),但是似乎有点草率,并且可能会产生比仅进行2个DB调用更多的开销。

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 [...]" 您的数据在表中是以人类可读的形式存在的,但是您却反对通过JSON发送数据,因为它是“以人类可读的形式[...]”

  • 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). 该表是所有tds,trs的庞大对象,但是您介意通过JSON发送相同的数据(这可能会占用更少的空间)。

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). 但是,如果您真的反对JSON并且不介意该表,则可以从该表提取数据(无论如何发送)。 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 ;-) 这是著名的View Controller Model模式,控制器在其中查询View以收集用作模型的数据;-)

A much better idea (but you are against sending JSON) would be to send the data with JSON, and generate the table with Javascript. 一个更好的主意(但您反对发送JSON)是使用JSON发送数据,并使用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). 甚至可以将未显示在表中的数据放在此处(例如,不可见的跨度),并使用一些琐碎的编码(如rot13(未包含在答案中,但广泛使用))使临时复制/粘贴无法访问。 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>

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 (ie make an ajax request) in order to have the browser cache it. 如果负载很大,您可能希望将其作为外部文件来源(即发出ajax请求),以使浏览器对其进行缓存。 However, in most cases, minimize the number of HTTP requests as much as possible. 但是,在大多数情况下,请尽可能减少HTTP请求的数量。 Personally I'd go with embedding the json into HTML unless it's maybe >20 kb zipped. 我个人将json嵌入到HTML中,除非它的压缩范围> 20 kb。

I would use a variation of #2. 我会使用#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. 是的,通过AJAX获取JSON,因为这将使页面加载更快,并且也更加灵活-也许在将来的某个时候,您将希望能够在没有表格的情况下显示地图,等等。

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. 但是,添加一个PHP 该类包装对数据源的调用,并由生成HTML的页面和生成JSON的页面使用。 This will make it easier to cache the results of the query, and will eliminate duplicate code. 这将使缓存查询结果更加容易,并且将消除重复的代码。

good choice I always pass data to the client in JSON, use this command 好的选择,我总是使用JSON将数据传递给客户端,请使用此命令

<?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 ;) 就这么简单,就像在客户端一样打印输出并遍历它;)

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

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