微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 允许在脚本运行完毕后单击链接

我试图找到一种方法,只有在特定功能完成运行后才允许用户点击链接.所以在我的情况下我有ejs模板,其中parapgraphs中有两个链接.单击第一个(“运行python”)激活一个需要一些时间才能完成的脚本.然后只有在它完成后(所以有“完成” – 来自行:console.log(‘完成’)打印在控制台上)下一个链接(“查看表格”)将是可点击的(或者是unhid)或类似的东西).

<h1>Search for a movie</h1>

<form action="results" method="GET">
    <input type="text" placeholder="search term" name="search">
    <input type="submit">
</form>

<p><a href="/run"> Run python </a></p>
<p><a href="/data"> See the table </a></p>

这是app.js代码

var express = require("express")
var app = express()
var request = require("request")
var PythonShell = require('python-shell');
app.set("view engine", "ejs")
app.engine('html', require('ejs').renderFile);

var thelist =[]

app.get("/", function(req, res){
    res.render("search")
})

var jsondata = ""


app.get("/results", function(req, res){
    var query = req.query.search
    var url = "http://www.omdbapi.com/?s=" + query + "&type=series&apikey=thewdb"

    request(url, function(error, response, body){
        if(!error && response.statusCode == 200){
            var data = JSON.parse(body)
            res.render("results", {data: data})
        }    
    })
})

app.get('/data', function(req, res) {
    //viewname can include or omit the filename extension
    res.render(__dirname + '/well.html'); 
});


app.get("/show/:id", function (req, res) {
    var id = req.params.id;
    thelist.push(id)
    console.log(thelist);
    res.redirect('/')
});

app.get("/run", function(req, res) {
            var pyshell = new PythonShell('script2.py');
            pyshell.send(JSON.stringify(thelist))
            pyshell.on('message', function (message) {
    // received a message sent from the Python script (a simple "print" statement)
            jsondata += message
            });

// end the input stream and allow the process to exit
            pyshell.end(function (err) {
             if (err){
               throw err;
                };

            console.log('finished');
            });
            res.redirect('/')
            thelist = []
});

app.listen(process.env.PORT, process.env.IP, function(){
    console.log("Movie App has started!!!");
})

解决方法:

你可以用ajax来做,正如埃米尔在他的回答中所说,
但既然你使用的是ejs模板引擎,为什么不使用呢?
(您只需将.html模板文件扩展名更改为.ejs).

此外,我认为您最好的选择是不使用res.redirect.
最好使用res.render并将参数传递给视图,认情况下设置为false.

一个基本的例子:

server.js

// ...
app.get("/", function (req, res) {
  res.render("search", { active: false });
})

// ...
app.get("/run", function (req, res) {
  // ...
  pyshell.end(function (err) {
    if (err) throw err;
    console.log('finished');
    res.render("search", { active: true });
  });
});

search.ejs

<p><a href="/run">Run python</a></p>
<p>
  <%if (active) { %>
    <a href="/data">See the table</a>
  <% } else { %>
    See the table
  <% } %>
</p>

现在,如果python脚本完成,则只能单击“查看表”链接.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐