簡體   English   中英

使用JQuery和Ajax提交表單

[英]Form Submission using 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.stop傳播
  • 返回假

所有人一無所獲。 該表單確實提交了數據並將數據存儲到數據庫。 但是,ajax部分並沒有像我期望的那樣安靜。

有人知道我在這里想念什么嗎?

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;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM