繁体   English   中英

如何在Ajax函数上获取回调

[英]How to get a callback on an Ajax function

我试图找出服务器上是否存在文本文件(注释)。 如果要返回“是”,否则返回“否”。 我能够成功地将其发送到警报中(针对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));

另请参阅如何返回异步调用的响应? 为什么在函数内部修改变量后,变量没有改变? -异步代码参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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