简体   繁体   中英

How to run python script on JS(button onclick)

How to run django script in js. I need to use IMDb API on onclick method to get id of movie user is searching.

how can I do it?

I am still begginer in django so dont judge me :)

Here is my html for that part:

 <div class="form-inline mt-2 mt-md-0">
    <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" id="search_movie_textField">
    <button class="btn btn-outline-success my-2 my-sm-0" onclick="search_movie()" >Search</button>
  </div>

Here is my JS I am trying to write:

function search_movie(){
var sreach = document.getElementById("search_movie_textField").value;

id = //GET IMDB ID FROM SEARCH

window.location.href = '/movielist/movies/' + id; }

Try this:

function search_movie() {
    var search = document.getElementById("search_movie_textField").value;
    window.location.href = '/movielist/movies/' + search;
}

Codepen: https://codepen.io/anon/pen/bKxGbg

You should use ajax for this. If your directory structure is something like this, you can do the following.

your_django_app/
    __init__.py
    models.py
    urls.py
    views.py
    templates/
        your_django_app/
            search.html
    ....

Add a url in your urls.py for the search function

from django.urls import path
from . import views

app_name = "your_app_name"

urlpatterns = [
    .....
    path('search', views.search, name='search'),
    .....
]

And in the views.py write the function which will search for the movie ID.

from django.http import JsonResponse

def search(request):
    search_keyword = request.POST["search"]
    ......
    id = get_movie_id(search) # Your function to obtain the movie ID
    ......
    return JsonResponse({"id": id})

And finally the search.html should be something like this:

<div class="form-inline mt-2 mt-md-0">
    <form id="search-form">
        {% csrf_token %}
        <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" id="search_movie_textField" name="search">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
</div>

<script>
$("#search-form").on("submit",function(e){
    e.preventDefault();
    $.ajax({
        url : '{% url "your_django_app:search" %}',
        type: "POST",
        data: $(this).serialize(),
        success: function (data) {
            window.location.href = '/movielist/movies/' + data.id;
        },
        error: function (jXHR, textStatus, errorThrown) {
          alert(errorThrown);
        }
    });
});
</script>

Note: Don't forget to include jQuery

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