我一直在研究这段代码
$("#library").submit(function(e){
//return false;
e.preventDefault();
dataString = $("#library").serialize();
$.ajax({
type:"POST",
url:"<?= base_url() ?>index.php/library/comment",
data: dataString,
dataType: 'json',
success: function(data){
$("#librarycomment").val("");
$('#comment-list').prepend('<li><div class="avatar"><img src="<?= base_url();?>asset/css/library/images/picture.jpg">' +
'</div>' + '<div class="colset">' + '<div class="author">' + data.user +
' <strong>' + data.date + '</strong>' +
'</div>' + '<div class="comment-content">' +
data.text + '</div></div></li>').find("li:first").hide().slideDown('slow');
}
});
});
我希望在不刷新浏览器的情况下获得良好的表单验证。上面的代码有些不起作用。
我试图替换e.preventDefault();与
所有人都什么都不给。表单确实提交数据并将数据存储到数据库中。然而,ajax部分并不像我期望的那样运行安静。
有谁知道我在这里缺少什么?
答案 0 :(得分:0)
class somehelperclass
{
public function unserialize($input, $pIndex = 'data')
{
if(!isset($input[$pIndex]))
exit('index '.$pIndex.' is not exist');
parse_str($input[$pIndex], $input);
$post = array();
foreach($input as $index => $value)
{
$index = preg_replace('/\;/', '', $index);
$post[$index] = $value;
}
return $input;
}
public function jsonResponse($array)
{
header("Content-type: application/json");
echo json_encode($array);
exit();
}
}
// your controller
class Library extends CI_Controller
{
public function comment()
{
$this->load->library('somehelperclass');
$_POST = $this->somehelperclass->unserialize($_POST, 'data');
$this->somehelperclass->jsonResponse($_POST);
}
}
// js
$("#library").submit(function(){
that = $(this);
$.ajax({
type: "post",
url: "/index.php/library/comment",
data: {data: that.serialize()},
dataType: 'json',
success: function(response)
{
$("#librarycomment").val("");
$('#comment-list').prepend('<li><div class="avatar"><img'
+ ' src="/asset/css/library/images/picture.jpg"></div>'
+ '<div class="colset"><div class="author">'
+ response.user + ' <strong>' + response.date + '</strong>' +
'</div>' + '<div class="comment-content">' +
response.text + '</div></div></li>').find("li:first").hide().slideDown('slow');
}
});
return false;
});