2012-10-16 39 views
0

我想了解ajax的基础知识,但我真的无法使它工作。这是我正在尝试的。真的很简单ajax + codeigniter

文件: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")); 
    } 
} 


} 
?> 

什么时,我提交了我总是得到的是:错误:0 - OK 这意味着我甚至没有获得'成功'的功能。如果不是回声,我使用'return',那么我将进入成功函数(但显然我不能输出结果)。

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

+0

检查http://stackoverflow.com/questions/7573243/php-reload-page-when-adding-forms-maybe-needs-ajax/7573935#7573935 –

+0

我检查了。我仍然不确定如何解决它。 – Stergios

+0

我检查了你的代码,它完美地适用于我,所以这应该是一个配置问题。当你打开'yourpage/index.php/comment/create /'作为一个页面时会发生什么? –

回答

1

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

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

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

谢谢大家的时间!

+0

很高兴你有这个工作,它很有趣,它为什么这样工作 –

-1

enter image description here

要解决,你必须启用它在php.ini而不笨禁用压缩的压缩问题。