我试图查明服务器上是否存在文本文件(注释)。 如果是的话我想返回"is",如果没有则返回“否”。 我能够成功地将其放入警报中(对于 7 次出现中的每一次),但我想将其返回到原始 html 文档中,以便我可以在将来的代码中使用它。我正在这个网站上阅读有关回调的内容,但不确定如何实现它。
我尝试向成功函数添加一些回调代码,我在此处其他地方的示例中看到了这些代码,但不确定如何编辑我的函数调用:
tmpNoteFileSun 是一个文本字符串,与服务器上存储的文本文件的格式匹配。
函数调用(其中 7 个位于不同的位置,1 个代表一周中的每一天):
CheckNoteExist(tmpNoteFileSun);
var DoesTheNoteExist = ""; //code needs to go here that returns noteexists (as in the alert below).
我尝试将上面的内容更改为:
var DoesTheNoteExist = CheckNoteExist(tmpNoteFileSun);
console.log("Does Note Exist " + DoesTheNoteExist);
但在控制台中未定义。
Ajax 函数:
function CheckNoteExist(ThisNoteName, callback) {
var NoteFileName = ThisNoteName;
// Ajax to call an external php file, pass the notes filename to it and check if the file
// exists. If it does, change noteexists variable to Yes", else it is "no".
$.ajax({
url: 'ajaxfile_note_exists.php',
type: 'GET',
data: {NoteFileName: NoteFileName},
success: function(noteexists) {
alert("Does the note exist: " + noteexists);
callback && callback(noteexists);
}
});
}
外部 PHP 文件:
$filename = "upload/" . $_GET['NoteFileName'];
if (file_exists($filename)) {
$noteexists = "yes";
}
else {
$noteexists = "no";
}
echo $noteexists;
?>
最佳答案
您没有使用回调,这就是它的用途。
CheckNoteExist(ThisNoteName, val => console.log("Does Not Exist " + val));
另请参阅How do I return the response from an asynchronous call?和 Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
关于javascript - 如何获取 Ajax 函数的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57828338/