php - 使用 Ajax 和 PHP 导入 csv 将 csv 导入 mysql,而不是上传文件
问题描述
我有以下页面
- 索引.php
- 导入数据.php
我尝试使用 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"> </td>
</tr>
</table>
</body>
解决方案
我设法获得现在发布的信息,执行以下操作
$(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 行
推荐阅读
- sorting - 使用 Python 按字母顺序对文件内容进行排序
- html - 当我单击一个 div 时,其他移动
- r - 替换已弃用的软件的独特挑战 funs()
- python - 如何在不知道密钥的情况下找到下一级 dict?
- powershell - powershell raspbian 从 ps1 执行 Invoke-RestMethod
- laravel - 在除根页面之外的每个页面上加载 CSS、JS 和图像时出错
- python - Python - 如何使这个递归?
- apktool - apktool 反编译但不会重新编译
- javascript - 单击按钮时,如何编写按钮(在简单的登录页面上)以将某人连接到本地 wifi?
- python - 为什么 os.open 会产生 PermissionError 即使 os.R_OK 是真的?