0

我一直在研究这段代码

$("#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 部分并不像我期望的那样安静。

有谁知道我在这里想念什么?

4

1 回答 1

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;
});
于 2013-05-27T19:24:09.763 回答