真的很简单的ajax + codeigniter

时间:2012-10-16 20:54:02

标签: jquery ajax codeigniter

我正在努力学习ajax的基本原理,但我无法让它真正发挥作用。这就是我正在尝试的。

文件:create_comment.php(查看)

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>

<script>
   $(function(){
       $("#comment").submit(function(){

         var name = $("#name").val();


         $.ajax({
           type: "POST",
           url: "<?php echo base_url(); ?>index.php/comment/create",
           data: "name="+name,
           dataType: 'json',

           success: function(result){    
                $('#write').html(result.returnValue);
           },
           error: function(xhr, status, error) { 
                alert('Error: '+ xhr.status+ ' - '+ error); },

         });

         return false;  

      });
   });
</script>

<title>Untitled Document</title>
</head>

<body>
<h3>New Comment</h3>
<form id="comment" method="post">
<label>Name: </label><input type="text" id="name" name="name" /><br
<label>&nbsp;</label><input type="submit" value="Submit" />
</form>

<div id="write" ></div>
<!-- here is the script that will do the ajax. It is triggered when the form is submitted --></body></html>

文件:comment.php(控制器)

<?php

class Comment extends CI_Controller{

function  __construct() {

    parent::__construct();
    $this->load->helper('url');
}

function index(){

    $this->load->view('create_comment');


}

function create(){

    if($_POST) {
           echo json_encode(array("returnValue"=>"This is returned from PHP")); 
    }
}


}
?>

当我提交for时,我总是得到的是:错误:0 - 好的 这意味着我甚至没有获得“成功”功能。如果不是回声,我使用'return',然后我进入成功函数(但显然我无法输出结果)。

我知道这一定是最容易的问题,但我做错了什么?

2 个答案:

答案 0 :(得分:1)

伙计们我找到了解决方案。

我设置了$ config ['compress_output'] = TRUE;

如果我把它设置为FALSE一切正常!!

谢谢大家的时间!!

答案 1 :(得分:-1)

enter image description here

要修复压缩问题,您必须在php.ini中启用它,而无需从codeigniter禁用压缩。