0

show_page.php:

   <?

 session_start();
  include("includes/function.php");

$static = mysql_query("SELECT * FROM fb_pages WHERE user_id = '$_SESSION[user_id]' AND page_value = '1' ") or die(mysql_error());

            while($stat = mysql_fetch_array($static)) {

                    $page = $stat['page_name'];


                            echo json_encode($page);
  exit();

                    }       

ob_and_flush();     
?>  

and js code:

  <script type="text/javascript">

$.ajax({
type: "POST",
url: "show_page.php",
dataType: "JSON", //tell jQuery to expect JSON encoded response
success: function(response) {

 $('#page').html(response);
 }
});


 </script>  

I like show the result in <div id="page"></div> .

If run this code, the result is one page, and always one page, but if I delete in show_page.php , exit(); then result is good, show all page, but don't show webpage, I think, then may json. What this problem??

4

3 回答 3

1

您正在退出循环,因此它只处理第一行。您需要将所有结果收集到一个数组中,调用json_encode整个数组,然后退出。

$page = array();
while ($stat = mysql_fetch_assoc($static)) {
  $page[] = $stat['page_name'];
}
echo json_encode($page);
ob_end_flush();
exit();

但是,您的 jQuery 会:

$('#page').html(response);

response应该是 HTML,而不是数组。您需要将其更改为对响应中的每个页面名称执行某些操作的循环,例如

$.each(response, function(i, p) {
   $('#page').append($('<div/>', { text: p }));
});
于 2013-07-23T17:35:45.567 回答
0

这部分

 $page = $stat['page_name'];


 echo json_encode($page);

看起来 $page 不是数组,所以你不需要添加 json_encode() 函数。因此,您不需要 dataType: "JSON"

于 2013-07-23T17:32:49.407 回答
0

看起来您正在尝试输出多个 INDEPENDENT json 字符串。这行不通。代码应该更像:

$data = array();
while ($stat = mysql_fetch_array($static)) {
    $data[] = $stat['page_name'];
}
echo json_encode($data);

请记住,JSON 基本上是 javascript 赋值操作的右侧。您创建为 JSON 的任何内容都必须是有效的 javascript,例如

var foo = json_goes_here.

你正在做类似的事情

var foo = 'bar''baz';

相反,构建一个字符串数组,当 json 编码时,它更像

var foo = ['bar', 'baz'];
于 2013-07-23T17:36:04.903 回答