如何使用php和phpExcel从我的ajax调用获得响应?

时间:2017-03-29 18:01:19

标签: javascript php jquery ajax

我有2个文件index.php和file.php,我使用index.php附加我要转换为json的csv文件,我的file.php将其作为json返回,file.php有效完美并使用json_encode()返回json数组没有问题,但我没有得到ajax的日志答案!我希望有人可以帮我解决这个问题

<script type="text/javascript">
  $(document).on("ready", function(){
    $("#Data").click(function(e){
        tabla();
  });
  });
  function tabla(){
  _ajax("file.php","")
  .done(function(info){
    console.log(info);
    var csv= JSON.stringify(info);
    console.log(csv);
  });
}
//solicitud ajax para ahorra codigo
function _ajax(url,data){
  var ajax = $.ajax ({
      "method":"POST",
         "url": url,
        "data": data
  });
  return ajax;
}
</script>
<form method="post"  enctype="multipart/form-data">
      <br>
      <br>
    Adjuntar Archivo: <input type="file" id="file" name="file"/>
    <br>
    <br>
    <input type="submit" id="Data"  name="submit" value="Submit" />
    </form>

php代码:

header('Content-type: application/json');
if(isset($_FILES['file']['name'])){
    $file_name = $_FILES['file']['name'];
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);
    //Checking the file extension
    if($ext == "csv"){
      $file_name = $_FILES['file']['tmp_name'];
       $inputFileName = $file_name;
// Set your CSV feed
$feed = $inputFileName;
// Arrays we'll use later
$keys = array();
$newArray = array();
// Function to convert CSV into associative array
function csvToArray($file, $delimiter) {
  if (($handle = fopen($file, 'r')) !== FALSE) {
    $i = 0;
    while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
      for ($j = 0; $j < count($lineArray); $j++) {
        $arr[$i][$j] = $lineArray[$j];
      }
      $i++;
    }
    fclose($handle);
  }
  return $arr;
}
// Do it
$data = csvToArray($feed, ',');
// Set number of elements (minus 1 because we shift off the first row)
$count = count($data) - 1;
//Use first row for names
$labels = array_shift($data);
foreach ($labels as $label) {
  $keys[] = $label;
}
// Bring it all together
for ($j = 0; $j < $count; $j++) {
  $d = array_combine($keys, $data[$j]);
  $newArray[$j] = $d;
}
// Print it out as JSON
echo json_encode($newArray);
}else {
  echo "eror";
}
}

0 个答案:

没有答案