javascript - javascript生成的对象出现后立即消失

标签 javascript python

在单击按钮时,我正在调用 python 脚本并将结果填充到一个数组中。完成后,我创建 <a href>一样多<a href>对象作为数组的长度。问题是,一旦显示链接,它们就会立即消失。

Body:
//I obviously get the same effect by putting the onclick event in the submit button
window.onload = function() {
    alert("loaded");
    document.getElementById('submit_searchsubs').onclick = function () { 
        FindSubtitles();
    };
};

function FindSubtitles() {

        postData = {"movie": "Outlander", "season":"1", "episode":"2"};             
            $.ajax({
                url: "/cgi-bin/find_subtitles.py",
                type: "post",
                datatype:"json",
                async : false,
                data: {postData},
                success: function(response){
                    var subs = new Array();
                    var json = $.parseJSON(response);
                    for (var i=0;i<json.length;++i) {
                        subs[i] = new Array(json[i].IDSubtitle, json[i].SeriesEpisode, json[i].SubHash, json[i].SubDownloadsCnt, json[i].SeriesSeason, json[i].ZipDownloadLink, json[i].MovieName, json[i].id, json[i].SubFileName);
                    }
                    DisplaySubtitles(subs); //show the users the new words found in this subtitle
                } 
            })
            .fail(function(err) {
                alert("error" + err);
            });

    }

function DisplaySubtitles(subs) {
        var SubtitleDiv = document.getElementById("SubtitleDiv");
        var a = document.createElement('a');
        for (i = 0; i < subs.length; i++) {
            var linkText = document.createTextNode(subs[i][8]);
            a.appendChild(linkText);
            SubtitleDiv.appendChild(a);
        }
}

那么会发生什么:

  1. 页面加载
  2. alert("loaded") 在 window.onload 中触发时显示
  3. FindSubtitles 运行
  4. DisplaySubtitles 运行并且 <a>出现链接
  5. <a>链接消失并再次显示 alert("loaded")。

我不知道我是否应该使用 async: true ,因为在那种情况下我得到 [Object object]错误,这很奇怪,因为在我使用另一个脚本的情况下,否则它会卡住 UI。

有什么想法吗?

最佳答案

正如Kieveli 提到的,如果submit_searchsubs 是一个提交的表单按钮,它可能在提交后刷新页面。尝试使用 return false;绕过默认的浏览器 onclick 操作。

document.getElementById('submit_searchsubs').onclick = function () { 
    FindSubtitles();
    return false;
};

关于javascript - javascript生成的对象出现后立即消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35139197/

相关文章:

JavascriptExecutor (Selenium WebDriver C#) 不断返回空对象

javascript - Node.JS undefined 不是所需模块上的函数

javascript - 为什么浏览器提供禁用 Javascript 的选项?

javascript - 如何在 Node.js 上使用 co 模块捕获异常?

python - 从字符串列表中提取薪水

python - 如何在argparse中将store_true和值存储在互斥组中?

python - 如何让 gunicorn 记录未捕获的异常?

javascript - 从另一个文件访问 Ext Designer JsonStore

python - 使用 Python 修改 PCAP

python - 无法获取 pandas 数据框中特定变量的虚拟值