我想了解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> </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',那么我将进入成功函数(但显然我不能输出结果)。
我知道这一定是最简单的问题,但是我做错了什么?
检查http://stackoverflow.com/questions/7573243/php-reload-page-when-adding-forms-maybe-needs-ajax/7573935#7573935 –
我检查了。我仍然不确定如何解决它。 – Stergios
我检查了你的代码,它完美地适用于我,所以这应该是一个配置问题。当你打开'yourpage/index.php/comment/create /'作为一个页面时会发生什么? –