Ajax调用未执行

时间:2016-03-01 23:20:12

标签: javascript ajax

我有以下功能:

Recorder.uploadAudio = function(blob, filename){
      var reader = new FileReader();
      reader.onload = function(event){
        var data;
        data = event.target.result;
        $.post( "upload.php", { fname: filename, data: data } );
      };
      reader.readAsDataURL(blob);
      $.get( "get_files.php", function( data ) {
        $('#clips').html(data);
      });
    }

sript upload.php将文件保存到服务器,get_files.php刷新文件列表(它将所有音频文件加载到文件夹中并将其显示在列表中。)当我调试脚本时,upload.php不会t load,它在data = event.target.result行停止。并且,blob参数加载正常,它代表了一个音频文件。

编辑:这是upload.php代码:

<?php

function is_dir_empty($dir) {
  if (!is_readable($dir)) return NULL; 
  $handle = opendir($dir);
  while (false !== ($entry = readdir($handle))) {
    if ($entry != "." && $entry != "..") {
      return FALSE;
    }
  }
  return TRUE;
}

function get_latest_index($path) {
    $latest_ctime = 0;
    $latest_filename = ''; 

    $d = dir($path);

    while (false !== ($entry = $d->read())) {
      $filepath = "{$path}/{$entry}";
      // could do also other checks than just checking whether the entry is a file
      if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
        $latest_ctime = filectime($filepath);
        $latest_filename = $entry;
      }
    }
    $latest_index = preg_replace("/[^0-9]/","",$latest_filename);
    $latest_index = (int)$latest_index;
    $latest_index++;
    if ($latest_index < "10") {
        $latest_index = "0" . $latest_index;
    }

    return $latest_index;
}

// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,


$path = "audio/"; 
$d = dir($path);

if (is_dir_empty($d)) {
    $fname = "MyRecording00";
}
else{
    $fname = "MyRecording" . get_latest_index($path);
}



$filename = "audio/" . $fname . ".wav";
echo $filename;
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>

1 个答案:

答案 0 :(得分:0)

FileReader onload事件是异步的; $.post()$.get()异步返回结果。尝试在$.get() $.post()事件中包括onloadFileReader;在$.get()

的完整回调中致电$.post()
      var reader = new FileReader();
      reader.onload = function(event){
        var data;
        data = event.target.result;
        $.post( "upload.php", { fname: filename, data: data } )
        .then(function() {
          $.get( "get_files.php", function( data ) {
            $('#clips').html(data);
          })
        });
      };
      reader.readAsDataURL(blob);