2016-03-01 74 views
0

我有以下功能: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不加载,它停止在数据= 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

你是什么意思为“停止”完成回调中调用$.get()?它会抛出一个错误吗? –

+0

我在浏览器中设置了debbuger,我在上面提到的那一行以及下一行使用jquery post请求,并且它只是遍历它并转到下一个ajax调用(jquery获取get_files.php请求)。 – user3362334

+2

你期望在那里发生什么? '$ .post'是一个异步函数。 – Igor

回答

0

FileReaderonload事件是异步的; $.post()$.get()异步返回结果。尝试在onload事件FileReader之内包括$.get()$.post();的$.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);