【问题标题】:How to get a callback on an Ajax function如何获取 Ajax 函数的回调
【发布时间】: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


    【解决方案1】:

    你没有使用回调,这就是它的用途。

    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

    【讨论】:

    • 谢谢,我正在寻找放置代码的位置。在 Ajax 代码之后?还必须从函数名称中删除尾随 s。阅读您现在提供的链接。
    • 您可以将此代码放在函数范围内的任何位置。函数定义被提升,所以顺序无关紧要。
    • 我在几个地方试过了,它一直在循环提醒。必须终止浏览器会话才能停止它。在其他地方我得到最大调用堆栈大小超出 RangeError:最大调用堆栈。我肯定做错了什么。会继续努力的。
    • 您显示的代码中没有任何内容会导致它循环。
    • 我找不到任何导致循环的东西。不确定是什么问题。我想我只是要为每一天编写一个单独的 php 文件,并将每个值存储在单独的本地存储中。
    猜你喜欢
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 2021-09-11
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    相关资源
    最近更新 更多