javascript - 在 PythonAnywhere 上的 html 文件中运行脚本

标签 javascript python ajax web-applications flask

我正在尝试使用 Flask 框架运行 python 脚本。 主要目标是:

  • 提交数据(关键字)+ 单击按钮
  • 将关键字放在 python 脚本中
  • 在服务器上运行
  • 返回回复
  • 请求结果(Json)
  • 在 html 页面上打印结果

一些注释:

该脚本是来自第三方API的请求 我想在html页面中打印的结果只是一个数字。

API 脚本:

import indicoio
indicoio.config.api_key = 'YOUR_API_KEY'

# single example
print.indicoio.sentiment("Keyword")

经过一些研究,我发现了 2 个解决方案来解决我的问题,但我不知道如何实现代码。我是初学者,请放轻松。

我的应用程序.py

from flask import Flask

app = Flask(__name__, static_url_path="/static", static_folder='/home/dubspher/mysite/static')

@app.route('/')
def static_file():
    return app.send_static_file('index.html')

if __name__ == "__main__":
    app.run()

第一种方法:

pip install requests
import requests
data = {"keyword":"LoremIpsum"}
r = requests.put("Request_Page_Link/",data = data )
data = r.json 
print("data")

第二种方法:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/my-link/')
def my_link():
  print 'I got clicked!'

  return 'Click.'

if __name__ == '__main__':
  app.run(debug=True)

处理 POST 和 GET 请求的代码:

<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue">
<script>
$('#id').click(function(){

 $.ajax({
      type:'get',
      url:<YOUR SERVERSIDE PAGE URL>,
      cache:false,
      data:<if any arguments>,
      async:asynchronous,
      dataType:json, //if you want json
      success: function(data) {
        <put your custom validation here using the response from data structure >
      },
      error: function(request, status, error) {
        <put your custom code here to handle the call failure>
      }
   });
});
</script>

如果我需要添加更多信息,请告诉我。谢谢!

最佳答案

我建议使用 fetch 它是纯 JavaScript 来在 js 中进行 url 调用。您可以执行 GET 调用,例如 fetch('/my-link')

fetch('/my-link')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })

在你看来做一些处理并返回jsonify(dict)输出/

关于javascript - 在 PythonAnywhere 上的 html 文件中运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44387822/

相关文章:

javascript - 如何在 IE、FF、Chrome 等上可靠地设置类 attr w/JavaScript?

php - 使用 php 或 Ajax 或 Jquery 提取 url 数据和图像

javascript - AJAX 是一种独立于 Javascript 的语言,还是一个 JavaScript 框架?

python - 如何在 django 模型中存储函数

python - 使用适当的变量类型将 CSV 文件从 redshift 导出到本地

python - 如何在python输入中交换字母?

javascript - Extjs组合作为自动完成搜索框,同步

javascript - Laravel 返回渲染的 html View ,不带\r\n -- json

javascript - 开发语法应用 SharePoint Online PrismJS

javascript - 如何在javascript中对数组进行一一处理?