CodeIgniter给了我错误404,但我可以在Firebug中看到响应

时间:2012-12-05 03:24:09

标签: php ajax codeigniter

我已经在SO中读过一些非常类似的问题,但没有一个解决方案适合我。

问题是,例如,视图中包含以下代码:

$.ajax({
url: 'periodista/json',
async: false,
dataType: 'json',
success: function (json) {
$.each(json, function(k,v){valores.push(v); });

}

我收到404 Not Found错误,但Firebug向我显示了响应(http://i.imgur.com/yG9cW.png)

我尝试使用file_get_contents函数从一个简单的php脚本中读取url响应,但它不起作用

$url="http://localhost/xampp/populus/wordpress/app/periodista/json";
$json = file_get_contents($url);

我得到了相同的答案(404错误,我可以在Firebug中读取响应)。

我尝试过使用“index.php”网址,没有index.php的网址以及htaccess的帮助,并使用完整的网址但没有任何效果。而且我没有使用wordpress。

我认为当我尝试访问视图时未加载控制器,但我不知道为什么。

编辑:我的控制器功能代码(我正在使用Ignited Datatables库):

    public function json()
{
    $datatables = new Datatables();
    $datatables->select('nro_boletin')->from('proyecto_de_ley');
    echo $datatables->generate();


    $data['title'] = "Periodista";
    $this->load->view('periodista/json', $data);

}

2 个答案:

答案 0 :(得分:0)

尝试设置内容类型json并输出它而不是加载视图,如:

public function json() {
    $datatables = new Datatables();
    $datatables->select('nro_boletin')->from('proyecto_de_ley');
    echo $datatables->generate();


    $data['title'] = "Periodista";
    $this->output
               ->set_content_type('application/json')
               ->set_output(json_encode($data));
   //OR
   header('Content-Type: application/json',true);
   echo json_encode($data);

}

由于您使用的是ajax,因此您的函数称为

$.ajax({
    url: 'periodista/json', <-- your controllers function
    data: {"test" : "test" },
    async: false,
    dataType: 'json',
    success: function (json) { //output from your json function
          $.each(json, function(k,v){valores.push(v); });
    }

答案 1 :(得分:0)

我有类似的问题,我不得不手动设置标题。

public function get_prev_input_data()
{
    header("HTTP/1.1 200 OK");
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");

    $userdata = [
        "id" => 5,
        "username" => "captain hook",
    ];

    $prev = [
        "a1" => 123,
        "a2" => 46,
    ];
    $response = [
        "userdata" => $userdata,
        "previnput" => $prev
    ];
    echo json_encode($response);
}

所以你应该添加这一行

    header("HTTP/1.1 200 OK");
json()函数中的

相关问题