【问题标题】:json and php interegationjson和php集成
【发布时间】:2014-02-24 07:39:22
【问题描述】:

我使用 getJson() 函数通过 php 从服务器动态检索内容。代码是这样的:

function loadContent(url){
        $.getJSON("content.php", {cid: url, format: 'json'}, function(json) {
                $.each(json, function(key, value){
                    $(key).html(value);
                });
            });
        }

content.php 从 mysql 获取一些数据并生成一个数组并将其编码为 json 格式数组,然后使用 JavaScript 在 main_page.html 中打印它。我想要做的是 content.php 的输出是一个字符串(或数组中的一行)和 html 代码(结合来自 mysql 的数据)。因为我不想只打印一个数组。例如,我希望 content.php 输出是这样的:

<div id="content">
  <div id="one">
  some html code combined with data from mysql.
  </div>
  <div id="two">
  some html code combined with data from mysql.
  </div>
  .
  .
  .
</div>

所有这些都打印在 main_page.html 中的 &lt;div id="main"&gt; ..output of content.php.. &lt;/div&gt; 中。所以json函数不必循环这段代码 $.each(json, function(key, value){ $(key).html(value);} 并打印一份。

【问题讨论】:

    标签: php json getjson


    【解决方案1】:

    如果我理解正确,那么您可以使用 $.get() 来达到预期的效果。

    function loadContent(url){
        $.get( "content.php", {cid: url}, function( data ) {
            $( "#content" ).html( data );
        });
    }
    

    并修改您的 content.php 以返回纯 html 而不是 json 编码的数据。

    <?php
    $stmt = $dbh->prepare("SELECT name FROM items");
    $stmt->execute();
    $result = $stmt->fetchAll();
    $i = 1;
    
    foreach($result as $item) {
        echo '<div id="item' . $i . '">' . $item['name'] . '</div>';
    }
    ?>
    

    【讨论】:

    • 谢谢老兄,它工作得很好!但我现在有另一个问题。我使用 pushstate() 和 popstate() 在浏览器中虚拟地创建历史链接(结合 get(url))。为了使用上面的代码,我创建了所有链接来解析 content.php 的值。例如&lt;a href="1"&gt;...&lt;/a&gt; 所以 content.php 得到 id=1。但是浏览器显示 www.mysite.com/1 并且当我刷新页面时它显示 404 因为正在尝试查找文件 1。我希望 www.mysite.com/1 将“1”解析为 content.php并且链接为&lt;a href=/1&gt;...&lt;/a&gt;(或与上述相同,不介意)。
    • 您可以使用 .htaccess 将 url 中 content.php 之后的所有内容重写为 id。
    • 我有两页。主页面是 index.php,另一个是 content.php,它使用 get(url) 生成要在 index.php 中检索的数据。当您访问 www.mysite.com 时,如何显示 index.php。当您访问 www.mysite.com/1234 以显示 index.php 并从 id=1234 的 content.php 中检索数据时?这是用 .htaccess 完成的吗?你知道 .htaccess 必须有什么代码吗?
    • 我正在尝试做这样的事情:html5.gingerhost.com 如果您看到代码,您会看到它使用 content.php 来生产数据,但如果您访问 content.php?id=London 它只显示文本,如果您访问html5.gingerhost.com/London,它会显示整个站点,其中包含来自 content.php 的数据。这就是我想做的事情
    猜你喜欢
    • 2010-09-15
    • 2011-05-08
    • 2017-02-23
    • 2010-12-27
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 2013-04-01
    相关资源
    最近更新 更多