Data passing from HTML text input to python script

时间:2018-01-11 08:36:12

标签: javascript jquery python ajax django

I am creating a web scrapping application, using Django, which scraps the imdb website and lists the movie names based on what users types in the text field[suppose if user types 'b', it lists all the movie names starting with letter 'b'] I have a html text input and a button.

<body>
    <h1>The IMDB Scrapper</h1>
    <form method="POST" action="">
        <input type="text" name="name" placeholder="Iron Man..">
        <input type="submit" value="Search">
    </form>
</body>

I also have a python script which scraps the data from the website, using the hardcoded keyword.

I want to send the text input data to this python script when the button is pressed and process this data and send send the result hack to the same HTML page for display.

1 个答案:

答案 0 :(得分:0)

是的,你可以轻松地做到这一点:

  • 制作一个将start参数作为JSON
  • 的视图

Python示例:

class MyJsonForAjaxView(generic.View):

    def get(self, request, *args, **kwargs):
        if my_scrap_is_finished:
            return JsonResponse({'finished': True}, safe=False)
        return JsonResponse({'finished': False}, safe=False)
  • 使用POST方法在JavaScript(= AJAX调用)中调用该视图:

JavaScript代码:

$.ajax({
    method: 'post',
    type: 'json',
    cache: false,
    url: 'my_json_url',
    data: {'lat': your_lat, 'lgn': your_lgn}
}).done(function(data) {
    alert('call successfull!!!');
    /* data is filled with Django result, here {'finished': value} */
    if (data.finished) {
        /* handle finished */
    } else {
        /* do a small animation to show the user something is running */
    }
    /* todo: remember the call has been made and it s registered on Django side */
}).fail(function(data) {
    alert('fatal error!');
}).always(function() {
    /* whatever the result, always do something here */
});

你可以在后台执行此操作,禁用&#34;发送&#34;按钮,并在服务器的AJAX中每3秒询问一次。