无法让getJSON与codeigniter一起使用

时间:2013-03-18 00:18:02

标签: javascript ajax json codeigniter

我正在尝试使用getJSON,以便从数据库中获取最新信息。到目前为止我所做的是将它存储到一个数组json_encode(the array)中。这是有效的,因为我可以看到视图上的信息,但问题是ajax方法不会捡起它。也许我错过了一些非常愚蠢的东西。

控制器:

public function insertJSON()
{
    $this->load->model("values");
    $queryresults = $this->values->getDb(); 
    $arr = array();

    foreach($queryresults as $row)
    {
        $arr[] =  $row->postcode;
    }

    $data['arr'] = $arr;    
    echo json_encode($arr); 
    $this->load->view('answer', $data);

}

查看:

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
    <script>            
        $.post('/localhost/codeigniter/index.php/welcome/insertJSON', function(data) {
            alert(data);
        });
    </script>
    </script>
</head>
<body>
</body>
</html>

$ arr变量的转储:

array(4) {
  [0]=>
  string(5) "test1"
  [1]=>
  string(5) "test2."
  [2]=>
  string(5) "test3"
  [3]=>
  string(5) "test4"
}

3 个答案:

答案 0 :(得分:1)

您正在通过调用$data)将$arr数组(包含$this->load->view('answer', $data);)发送到视图,就在它回显JSON数据之前。

所以你要做的就是在任何html或javascript包含json编码$arr的纯文本之前调用一个顶部的视图。

这显然是错误的而不是你想要的。

您应该执行以下任一选项:

  1. 在视图$arr&gt;处回显<head <script>内的部分 标签。您不必使用AJAX调用。
  2. 只是回应 $arr在控制器上,但不要在它之后调用视图。你应该 可能会为此制作另一个Controller。一个回应$arr和。{ 一个叫视图。这样你就可以对第一个进行AJAX调用 控制器。
  3. $arr传递给只会回显JSON编码数据的视图。 这与选项#2类似,但它使用View来显示 数据而不是Controller,这是遵循MVC模式的最合适方式。 控制器不应回应任何东西。
  4. 我建议遵循选项#3。

答案 1 :(得分:1)

因此。如果你想回显一个可以使用ajax获取它的JSON obj,那么你需要确保你的页面的输出mime类型可以提供JSON数据。

还注意到你不能用你想要的json数据来回应你的任何其他东西。正如我在你的代码中看到的那样你回显json然后加载一个视图!你需要把它分成两个单独的页面

修正:

public function _JSON()
{
    $this->load->model("values");
    $queryresults = $this->values->getDb();

    $arr = array();

    foreach($queryresults as $row)
    {
       $arr[] =  $row->postcode;
    }

    return $arr;

}


public function json_body(){
    $this->load->view('answer',array('data'=>$this->_JSON()));
}


public function getJSON(){
    $this->output
    ->set_content_type('application/json')
    ->set_output(json_encode($this->_JSON()));
}
///note that $this->_JSON() now return ur $arr so u can use it in many methods.

现在加载页面你可以转到/json_body'重命名为你想要' 和js应该是

<script>
$.post('<?=base_url('welcome/getJSON')?>', function(data) {
alert(data);
});
</script>
<!--notice that base_url show echo out ur url base on ur config.php file-->

注:

函数getJson使用CI Output类的功能来设置页面的mime类型,并确保此数组是唯一的输出。这不是必须的,而是它的最佳实践。如果你想要你可以用简单的echo json_encode($this->_JSON());重新使用所有3行,它也会起作用!

答案 2 :(得分:0)

我猜问题是您的帖子网址:

$.post('//localhost/codeigniter/index.php/welcome/insertJSON', function(data) {
   alert(data);
 });

你错过了双斜线(//)