文件上传后 Ajax 未收到成功响应

发布于 2025-01-16 08:23:43 字数 2626 浏览 0 评论 0原文

我刚刚开始使用 Ajax,也尝试为此找到解决方案。

问题是:

我将 .csv 上传到服务器。这很好用。但上传“成功”后ajax调用不会响应。既不完成也不出错。它什么也没显示。甚至没有一个空警报。只是什么都没有。我在日志中也没有找到任何内容。

当我单击上传按钮而不选择要上传的文件时,我会收到成功的响应...

以下是代码:

upload.php

<?php
header('Content-type: application/json');
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$response[] ='';

  if(move_uploaded_file($_FILES["file"]["tmp_name"],$target_file))
  { 
    //$response['message'] = "File was uploaded!";
    $response['message'] = csvToJson($target_file);
  }
  else
  { 
    $response['message'] = 'Sorry, there was an error uploading your file.'; 
  }

echo json_encode($response);


function csvToJson($file) 
{
    // open csv file
    if (!($fp = fopen($file, 'r'))) {
        die("Can't open file...");
    }
    
    //read csv headers
    $key = fgetcsv($fp,"1024",";");
    
    // parse csv rows into array
    $json = array();
        while ($row = fgetcsv($fp,"1024",";")) {
        $json[] = array_combine($key, $row);
    }
    
    // release file handle
    fclose($fp);
    
    // encode array to json
    return $json;
}
?>

upload.js

$(document).ready(function(e)
{
    // Submit form data via Ajax
    $("#form").on('submit', function(e)
    {
        e.preventDefault();
        var form_data = new FormData($(this)[0]);  
        $.ajax({    
            type: 'POST',
            url: 'upload.php',
            data: form_data,
            contentType: false,
            cache: false,
            processData:false,
            success: function(response)
            { 
                //var json = $.parseJSON(response)
                alert(response);
            },
            error: function(error){
                console.log("Error:");
                console.log(error);
           }, 
           complete: function(response){
            alert(response);
           }

        });
    });
});

index.php 中的表单

<form id=form enctype="multipart/form-data">
        <input type="file" name="file" id="file">
        <input type="submit" value="Upload Excel" name="submit">
</form>

最后我想要一个包含以下内容的 json上传的文件。但现在如果文件上传则输出为零。

感谢您的任何建议!

编辑解决方案:

问题是不同的。 我必须将 csvToJson 的输出格式化为 UTF-8。之后我得到一个 json 作为响应。

格式化为 UTF-8 的函数(从这里的另一篇文章中获取)

function utf8ize($d) {
  if (is_array($d)) {
      foreach ($d as $k => $v) {
          $d[$k] = utf8ize($v);
      }
  } else if (is_string ($d)) {
      return utf8_encode($d);
  }
  return $d;
}

I just started with Ajax and also tried to find a solution for this.

Here is the problem:

I upload a .csv to a server. This works just fine. But after the upload "success" in the ajax call won't respond. Neither does complete or error. It shows nothing. Not even an empty alert. Just nothing. I also didn't find anything in the logs.

When I click the upload button without chosing a file to upload I get a response from success...

Here is the code:

upload.php

<?php
header('Content-type: application/json');
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$response[] ='';

  if(move_uploaded_file($_FILES["file"]["tmp_name"],$target_file))
  { 
    //$response['message'] = "File was uploaded!";
    $response['message'] = csvToJson($target_file);
  }
  else
  { 
    $response['message'] = 'Sorry, there was an error uploading your file.'; 
  }

echo json_encode($response);


function csvToJson($file) 
{
    // open csv file
    if (!($fp = fopen($file, 'r'))) {
        die("Can't open file...");
    }
    
    //read csv headers
    $key = fgetcsv($fp,"1024",";");
    
    // parse csv rows into array
    $json = array();
        while ($row = fgetcsv($fp,"1024",";")) {
        $json[] = array_combine($key, $row);
    }
    
    // release file handle
    fclose($fp);
    
    // encode array to json
    return $json;
}
?>

upload.js

$(document).ready(function(e)
{
    // Submit form data via Ajax
    $("#form").on('submit', function(e)
    {
        e.preventDefault();
        var form_data = new FormData($(this)[0]);  
        $.ajax({    
            type: 'POST',
            url: 'upload.php',
            data: form_data,
            contentType: false,
            cache: false,
            processData:false,
            success: function(response)
            { 
                //var json = $.parseJSON(response)
                alert(response);
            },
            error: function(error){
                console.log("Error:");
                console.log(error);
           }, 
           complete: function(response){
            alert(response);
           }

        });
    });
});

the form in index.php

<form id=form enctype="multipart/form-data">
        <input type="file" name="file" id="file">
        <input type="submit" value="Upload Excel" name="submit">
</form>

In the end I want a json back with the content of the uploaded file. But right now there is zero output if the file is uploaded.

Thanks for any advice!

EDIT for Solution:

The problem was something way different.
I had to format the output from csvToJson to UTF-8. After that I get a json as the respone.

Function for formatting to UTF-8 (got it from another post here)

function utf8ize($d) {
  if (is_array($d)) {
      foreach ($d as $k => $v) {
          $d[$k] = utf8ize($v);
      }
  } else if (is_string ($d)) {
      return utf8_encode($d);
  }
  return $d;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

著墨染雨君画夕 2025-01-23 08:23:43

解决方案,但无法标记它:

问题完全不同。我必须将 upload.php 中 csvToJson() 的输出格式化为 UTF-8。之后我得到一个 json 作为响应。

格式化为 UTF-8 的函数(从这里的另一篇文章中获取)

function utf8ize($d) {
  if (is_array($d)) {
      foreach ($d as $k => $v) {
          $d[$k] = utf8ize($v);
      }
  } else if (is_string ($d)) {
      return utf8_encode($d);
  }
  return $d;
}

Solution, but cannot mark it:

The problem was something way different. I had to format the output from csvToJson() in upload.php to UTF-8. After that I get a json as the respone.

Function for formatting to UTF-8 (got it from another post here)

function utf8ize($d) {
  if (is_array($d)) {
      foreach ($d as $k => $v) {
          $d[$k] = utf8ize($v);
      }
  } else if (is_string ($d)) {
      return utf8_encode($d);
  }
  return $d;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文