简体   繁体   中英

Button with full ajax flask implementation doing absolutely nothing

I'm trying to use a custom search bar on my flask app. I didn't managed to associate it to a form (or flask-wtform) and retain its animations. Therefore i choose to implement ajax, wich i'm also very interested to see working with flask. My problem is that no matter what i do, button does absolutely nothing!

HTML

{% block header %}
<div class="py-5 bg-image-full bgpic1">
  <img class="logotipo img-fluid d-block mx-auto" src="/static/img/cerveweb_inverted.png">
  <div class="searchBox">
    <input id="txtBusqueda" class="searchInput" type="text" placeholder="Buscar">
    <button id="btnBusqueda" class="searchButton">
      <i class="fas fa-search"></i>
    </button>
  </div>
</div>
{% endblock %}

Javascript

<script type="text/JavaScript">
  function buscar(){
    alert("2");
    var texto = $("#txtBusqueda").val();
    $.ajax({
      url: "{{url_for('buscar')}}",
      type: 'POST',
      data: {'data':texto},
      contentType: 'application/json;charset=UTF-8'      
    });
  };

  $("#btnBusqueda").click(function(){
    console.log("1");
    buscar();
  });  
</script>

Flask

@main.route('/buscar', methods=['GET', 'POST'])
def buscar():
    # Viene de un AJAX
    if request.method == "POST":
        texto = request.json['data']
        flash("Has buscado: {}".format(texto), "info")
    return render_template('index.html')

EDIT: Enclosing the scripts of the Jinja template, extending the functionality of a block of a base template made it work. However i'm confused about it, shouldn't scripts suvirve the rendering?. 在此处输入图像描述

Also, for some reason now it is pointing out that its a bad request: 在此处输入图像描述

This is the current code of the script and flask 在此处输入图像描述

It appears that flask has no good compatibility with Ajax, you have to switch to json to handle the Ajax request. Wich in medium to bigger sized app models with sqlalchemy is a pain. My approach was to map sqlalchemy objects directly to json counterparts using marshmallow ORM. Turning the app into a mix of classic flask-wtf and api rest. I must clarify that I did this refactor with time as major factor, prioritizing speed over performance.

There are some pretty elegant solutions out there that don't need such mix, but I could not stop to analize them in depth. They just could not compete with the very short amount of extra lines of code I needed. (around 3 per model class, and 2 for to call it)

However, I did not manage under any circumstances to make flask respond correctly the variables to Ajax. This problem was temporarily fixed using flask session, wich works line a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM