2013-05-27 242 views
0

我一直在这个代码表单提交使用jQuery和AJAX

$("#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 + 
             '&nbsp;<strong>' + data.date + '</strong>' + 
             '</div>' + '<div class="comment-content">' + 
             data.text + '</div></div></li>').find("li:first").hide().slideDown('slow'); 
     } 
    }); 
}); 

如果我想有一个漂亮的表单验证,而不必刷新浏览器。上面的代码有些不起作用。

我试图替换e.preventDefault();与

  • e.stopPropagation
  • 返回假

所有给予什么都没有。表单提交数据并将数据存储到数据库。然而,ajax部分并不像我期望的那样安静。

有谁知道我在这里错过了什么?

+0

你可以在成功函数中返回false或preventdefault吗? – FLX

+0

嗨FC感谢您的回复。即使我把这些放在成功之中,它仍然行不通。但是,我通过从.submit()更改为.click()来找到解决方法。很明显,我必须改变我的表单以及

并创建一个按钮(而不是提交按钮)。 – Jeremy

+0

我不知道这是否是一种更好的方式,只需点击用户无法用“Enter”键提交,这对可访问性就不好。也许替换点击('提交')。 – FLX

回答

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 + '&nbsp;<strong>' + response.date + '</strong>' + 
      '</div>' + '<div class="comment-content">' + 
      response.text + '</div></div></li>').find("li:first").hide().slideDown('slow'); 
     } 
    }); 
    return false; 
});