2013-10-22 19 views
0

我使用getJson()函数从php中动态检索服务器的内容。该代码是这样的:json和php interegation

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> 

而这一切将其打印在<div id="main"> ..output of content.php.. </div>在main_page.html。因此,json函数不必循环此代码 $.each(json, function(key, value){ $(key).html(value);} 并完成一个打印。

回答

0

如果我理解正确,那么您可以使用$ .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>'; 
} 
?> 
+0

谢谢你,他工作得很好!但我现在有另一个问题。我使用pushstate()和popstate()虚拟地在浏览器中创建历史链接(与get(url)结合)。要使用上面的代码,我将所有链接都解析为content.php。例如 '...'所以content.php的id = 1。但浏览器显示www.mysite.com/1,当我刷新页面时,它显示404正在尝试查找文件1.我希望www.mysite.com/1将'1'解析为content.php并且链接为 '...'(或者与上述idont相同)。 – user2901167

+0

你可以使用.htaccess来重写URL中的content.php到id之后的所有内容。 – ronalds

+0

我有两页。主页是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必须有? – user2901167