简体   繁体   中英

how to get data in the success of ajax

I have the following ajax function:

reader.onload = function(event){
    var fd = new FormData();
    var Name = encodeURIComponent('audio_recording_' + new Date().getMinutes() + '.wav');
    console.log("name = " + Name);
    fd.append('fname', Name);
    fd.append('data', event.target.result);
    $.ajax({
        type: 'POST',
        url: 'upload.php',
        data: fd,
        processData: false,
        contentType: false,
        success: function(data){
            //console.log(data);
             $.ajax({
                    type: 'POST',
                    url: 'readFile.php',
                    data: {"fileName":fileName},
                    success: function(data){
                        console.log(data);
                    }
                });
        }
    });
};      
  1. first question: I want to retrieve the data from the second success function to use it later in the code.how could that happen?

  2. second question: the data is an audio file.Is there is a special way to get audio data, or we can get it the same way as any data?In my php server side of the second ajax, I'm reading an audio file and want to use its data.I did simple file open and get contents.does that work for audio files?

server-side code:

<?php
$fileName=$_POST["fileName"];

$dh = opendir('upload/');
$contents = file_get_contents('C:/wamp/www/JSSoundRecorder/upload/'.$fileName);
// echo $contents;
echo $fileName;

This is a bad practice in general, but what you could do is specify a global variable at the start, and then assign data to that variable inside the success. The issue with this is that you can't be certain that the ajax has completed and your variable has been set, before you need to use it.

var mySuccessVar = null;

...
success: function(data) {
    mySuccessVar = data;
}

... // later in the code:
if (mySuccessVar != null) {
    yourFunction(mySuccessVar);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM