首页 > 解决方案 > 使用 Ajax 和 PHP 导入 csv 将 csv 导入 mysql,而不是上传文件

问题描述

我有以下页面

我尝试使用 ajax 将 csv 文件导入 MySql 我在网上使用了一些示例,但仍然无法使用 index.php

开头的脚本文件:

$(document).ready(function(){

    $("#but_import").click(function() {
        var formData = new FormData($("#import_form"));     
            $.ajax({
                url:"importData.php",
                data:formData,
                type:'POST',
                success:function(response) 
                {
                    var resp = $.trim(response);
                    $("#output").html(resp);
                }else[

                    $("#output").html("Error");

                });

    });
   }); 

脚本后的 HTML:

<html>
<head>
    <title>Import CSV file data to the MySQL using PHP</title>

</head>
<body>
 <form id="import_form" method="post" action="" enctype="multipart/form-data" >
        <table width="100%">

            <tr>
                <td style="width: 58px">
                    <input type='file' name="score_file" id="score_file">
                </td>

            </tr>
            <tr>
                <td colspan="2" >
                <input type="button" id="but_import" name="but_import" value="Import File"></td>
            </tr>

        </table>
    </form>


<table style="width: 100%">
    <tr>
        <td id="output">&nbsp;</td>
    </tr>
</table>
</body>

标签: phpmysqlajax

解决方案


我设法获得现在发布的信息,执行以下操作

$(document).ready(function() {

$("#but_import").click(function() {
    var formData = new FormData($('score_file')[0]);        



    alert(formData);    


        $.ajax({
             url: 'importData.php',
               data: formData,
              type: 'POST',
              contentType: false, 
                 processData: false,                
                 success:function(response) {
                        var resp = $.trim(response);
                        $("#message").html("yes");

                        }
        });

});

});

现在在 php 表单上位我收到以下错误 Undefined index: score_file in importData.php on line 6

这是html文件中的输入框

<form id="import_form" name ="import_form" method="post" action="post" enctype="multipart/form-data" >
        <table width="100%">

            <tr>
                <td style="width: 58px">
                    <input type='file' name="score_file" id="score_file">
                </td>

            </tr>
            <tr>
                <td colspan="2" >
                <input type="button" id="but_import" name="but_import" value="Import File"></td>
            </tr>

        </table>
    </form>

和 php 文件的前 2 行

 $csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
if(!empty($_FILES['score_file']['name']) && in_array($_FILES['score_file']['type'],$csvMimes)){

错误在第 2 行


推荐阅读