使用 ajax 提交表单时无法从视图中获取控制器中的字段数据

Cannot get field data in controller from view when submiting form using ajax

我正在使用 codeigniter,但是当我使用 ajax 提交表单时,我无法将字段数据从视图获取到控制器。从过去的 2 天开始,我正在研究它,但找不到解决方案。当我打印字段值时,它显示空白,即没有值。 我只想用ajax提交数据,不能正常发帖。请帮助解决我的问题。

这是我的代码:

View

$(document.body).on('click', '.postbtn' ,function(e){
    e.preventDefault();
    $('#posting_comment').submit();
});

<script type="text/javascript">
function sendCareerData()
{

    var fdata = new FormData(document.getElementById("posting_comment"));

    jQuery.ajax({
        type: "POST",
        url: "<?php echo base_url();?>"+"dashboard/do_upload",
        data: fdata,
        mimeType:"multipart/form-data", 
        contentType: 'text',
        cache: false,
        processData:false,
        dataType: 'html', 
        success: function (data) {
          alert("d"+data);
        },
            error: function(jqXHR, textStatus, errorThrown) 
        {
            console.log( errorThrown );  
        }

    });

    return false;
}

</script>

<form name="posting_comment" id="posting_comment" method="post" enctype="multipart/form-data" onsubmit="return sendCareerData()">
      <input name="comment_topic" id="comment" type="text" class=" postinputox" placeholder="Enter Topic..."/>
      <input id="file_upload" name="attachment_file" class="file_upload_icon" type="file"/>
      <input type="button" class="post postbtn" style="border: none;outline:none;" value="Post"/>
</form>

Controller:

public function do_upload()
    {
$comment_topic=$_POST['comment_topic'];
$attachment_file=$_POST['attachment_file'];
$config['upload_path'] ='./uploads/';
$config['allowed_types'] = 'gif|jpg|png||jpeg';
$config['max_width'] = 1000;
$config['max_height'] = 1000;
$config['max_size'] = 20000000;
$config['encrypt_name'] = FALSE;
$this->load->library('upload', $config);
$this->upload->do_upload($file_names);
    }

$comment_topic$attachment_file 都包含空白值。

在您的“查看”代码中,您犯了一些错误,如下所示:

1。按钮点击事件应该在 <script> 标签和 ready() 事件

<script>
$(document).ready(function() {
    $(document.body).on('click', '.postbtn' ,function(e){
        e.preventDefault();
        $('#posting_comment').submit();
    });
});
</script>

2。在 AJAX 中,将 contentType: 'text' 更改为 false

jQuery.ajax({
    type: "POST",
    url: "<?php echo base_url();?>"+"dashboard/do_upload",
    data: fdata,
    mimeType:"multipart/form-data", 
    contentType: false, // change 'text' to false
    cache: false,
    processData:false,
    dataType: 'html', 
    success: function (data) {
      alert("d"+data);
    },
        error: function(jqXHR, textStatus, errorThrown) 
    {
        console.log( errorThrown );  
    }

});

3。控制器更改:

您已使用 $_POST['attachment_file'] 访问上传的文件,应该是 $_FILES['attachment_file']

4。在上传函数中提供文件控制名称:

替换这个=>$this->upload->do_upload($file_names);

用这个 => $this->上传->do_upload("attachment_file");

在根目录中创建 “uploads” 文件夹。

经过这些更正后它正在工作...

完整代码:

控制器(demo.php):

<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Demo extends CI_Controller {

function __construct()
{
    parent::__construct();
}

function uploadview()
{
    $this -> load -> view("uploadview");
}

function do_upload()
{
    $comment_topic=$_POST['comment_topic'];
    $attachment_file=$_FILES['attachment_file']['name'];
    $config['upload_path'] ='./uploads/';
    $config['allowed_types'] = 'gif|jpg|png||jpeg';
    $config['max_width'] = 1000;
    $config['max_height'] = 1000;
    $config['max_size'] = 20000000;
    $config['encrypt_name'] = FALSE;
    $this->load->library('upload', $config);
    if($this->upload->do_upload("attachment_file")){
        echo "File $attachment_file Uploaded with Comment: $comment_topic";
    } else {
        echo "Upload Failed";
    }
}

查看(uploadview.php):

<html>
<head>
    <script type="text/javascript" src="<?php echo base_url() . "application/assets/public/"; ?>js/jquery-2.0.0.min.js"></script>
<script>
    $(document).ready(function() {
        $(document.body).on('click', '.postbtn' ,function(e){
            e.preventDefault();
            $('#posting_comment').submit();
        });
    });

    function sendCareerData()
    {
        var fdata = new FormData(document.getElementById("posting_comment"));

        jQuery.ajax({
            type: "POST",
            url: "<?php echo base_url();?>"+"demo/do_upload",
            data: fdata,
            mimeType:"multipart/form-data",
            contentType: false,
            cache: false,
            processData:false,
            dataType: 'html',
            success: function (data) {
                alert("result: "+data);
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                console.log( errorThrown );
            }

        });

        return false;
    }
</script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6">
            <br/>
            <form name="posting_comment" id="posting_comment" method="post" enctype="multipart/form-data" onsubmit="return sendCareerData()">
                <input name="comment_topic" id="comment" type="text" class=" postinputox" placeholder="Enter Topic..."/>
                <input id="file_upload" name="attachment_file" class="file_upload_icon" type="file"/>
                <input type="button" class="post postbtn" style="border: none;outline:none;" value="Post"/>
            </form>
        </div>
    </div>
</div>
</body>
</html>

输出:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>    
    <script>
      $(function () {
        $('#your_form_id').bind('submit', function () {
          $.ajax({
            type: 'post',
            url: 'your receiver page URL',
            data: $('#your_form_id').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });
          return false;
        });
      });
    </script>

这是你的答案

首先在你的控制器中复制并粘贴这段代码

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * User class.
 * 
 * @extends CI_Controller
 */
class Dashboard extends CI_Controller {

    /**
     * __construct function.
     * 
     * @access public
     * @return void
     */
    public function __construct() {

        parent::__construct();

               }

    public function index()
    {
           $this->load->library('upload');
          $this->load->helper(array('url'));
          $this->load->view('Test');
    }   
       public function do_upload()
           {
             $comment_topic=$this->input->post("comment_topic");
          $attachment_file=$_FILES["attachment_file"];
         $output_dir = "uploads/";
           $fileName = $_FILES["attachment_file"]["name"];
     move_uploaded_file($_FILES["attachment_file"]["tmp_name"],$output_dir.$fileName);
           }
    }

然后将此代码复制并粘贴到视图文件中

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script type="text/javascript">
function sendCareerData()
{

    var data = new FormData($('#posting_comment')[0]);


     $.ajax({
               type:"POST",
               url:"<?php echo site_url('Dashboard/do_upload');?>",
               data:data,
               mimeType: "multipart/form-data",
                contentType: false,
                cache: false,
                processData: false,
               success:function(data)
              {
                        console.log(data);

               }
       });

}

</script>

<form name="posting_comment" id="posting_comment" >
      <input name="comment_topic" id="comment" type="text" class=" postinputox" placeholder="Enter Topic..."/>
      <input id="file_upload" name="attachment_file" class="file_upload_icon" type="file"/>
      <input type="button" class="post postbtn" style="border: none;outline:none;" value="Post" onclick = "return sendCareerData()"/>
</form>

现在 运行 并查看有关 ajx 的更多信息阅读此 http://w3code.in/2015/10/how-to-edit-delete-and-update-data-without-refreshing-page-in-codeigniter/ and for file upload read this http://w3code.in/2015/09/upload-file-using-codeigniter/ and http://w3code.in/2015/10/how-to-upload-file-using-ajax-in-codeigniter/