【发布时间】:2019-09-06 20:41:54
【问题描述】:
我正在尝试找出服务器上是否存在文本文件(注释)。 如果是,我想返回“是”,如果不是,我想返回“否”。 我能够成功地将其变为警报(对于 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;
?>
【问题讨论】:
标签: javascript jquery ajax callback