2012-10-16 41 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而不笨禁用壓縮的壓縮問題。