简单的flask应用服务器通过ajax和jquery传递数据 [英] simple flask app server passing data with ajax and jquery

查看:45
本文介绍了简单的flask应用服务器通过ajax和jquery传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整天都在修改这个应用程序,试图将一些简单的信息传递到应用程序的后端.我正在使用一个简单的flask应用程序,并尝试使用ajax将数据从搜索查询发送到后端.但是,我已经完全失败了.任何帮助将不胜感激.

I've spent all day tinkering with this app trying to get some simple information passed to the back end of the application. I am using a simple flask app and trying to send data from a search query to the back end using ajax. However, I have been completely unsuccessful. Any help would be greatly appreciated.

下面是app.py

from scraper import scrape
from flask import Flask, render_template, jsonify, make_response, request
import json
app = Flask(__name__)

@app.route("/")
def index():

    entries = json.dumps(scrape("video games"))
    return render_template('index.html', entries= entries)

@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data():
    if request.method == "GET":
        #data = request.form("blah")
        #print("blah")
        search = request.json
        #new_search = json.dumps(scrape(data))
        return search
    return render_template('index.html')

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=5000)

和index.html

and index.html

    <!DOCTYPE html>
<html>

<head>
    <title>Flask app</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

  </head>
<body>

  <div class="topnav">
    <a class="active" href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
    <form name = "textbox" id = "textbox">
      <input id ="textbox" name="textbox" type="text" placeholder="Search..">
      <button type="submit">submit</button>
    </form>
  </div>

  <p>you searched: {{search}} </p>

  <div id="div1">
  <p id="p1"></p>
  <p id="p2"></p>
  </div>

<script>

var value = $('.textbox').val();
//alert(value);
$.ajax({
  type: 'POST',
  url: "/parse_data",
  data: JSON.stringify(value)
  contentType: 'application/json',
  success: function(data){
    alert("success")
  }
});



var jsonz = {{ entries|tojson }};



var s = JSON.parse(jsonz);



var i;
for (i = 0; i < s.length; i++) {
  var para = document.createElement("p");
  var node = document.createTextNode(s[i].product_name + "\n" + s[i].product_link);
  para.appendChild(node);

  var element = document.getElementById("div1");
  element.appendChild(para);
}




//document.getElementById("user").innerHTML =
//obj;
//"Name: " + obj.product_name + "<br>" +
//"Location: " + obj.product_link;
</script>



</body>
</html>

推荐答案

您的代码段存在一些问题,主要是:

Your code snippet has a few issues, mostly:

  • 您的AJAX请求未绑定到按钮单击事件,因此单击按钮不会执行任何操作.
  • 您有两个具有相同id 文本框的html元素,id应该是唯一的.
  • 要通过id获取html元素,请使用#textbox"
  • Your AJAX request is not bind to the button click event, so clicking the button does nothing.
  • You have two html elements with the same id textbox, id are supposed to be unique.
  • To get an html element by id use "#textbox"

在服务器端(烧瓶):

  • 使用请求的功能 get_json()
  • 要处理 POST 请求,您需要检查 POST 而不是 GET
  • Use the function get_json() of the request
  • To process the POST request you need to check for POST not GET

尝试像这样包装您的POST请求:

Try wrapping your POST request like this:

$("button").click(function (e) {
    e.preventDefault();
    var value = $("#textbox").val();
    alert(value);
    $.ajax({
        type: "POST",
        url: "parse_data",
        data: JSON.stringify({ "text" : value } ),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            alert(JSON.stringify(data));
        }
    });

});

还删除重复的ids textbox ,将表单的id更改为 textbox-form ,最后将您的 parse_data 函数更改为像这样的东西:

Also remove the duplicate ids textbox, change the id of the form to something like textbox-form, finally change your parse_data function to something like this:

@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data():
    if request.method == 'POST':
        search = request.get_json()
        return jsonify(search)
    return render_template('index.html')

这篇关于简单的flask应用服务器通过ajax和jquery传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆