从html页面上的javascript函数调用python方法以获取数据 [英] Calling a python method to fetch data, from a javascript function on the html page

查看:150
本文介绍了从html页面上的javascript函数调用python方法以获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • Google应用引擎
  • Django
  • Python
  • jQuery

我有一个下拉列表(国家)和一个文本框(城市){下拉列表和文本框由django格式生成},并由GeoIp库自动填充

I have a drop-down list (country) and a text-box (city) { the drop-down list and text-box are generated by a django-form} that get automatically populated by a GeoIp library

这些UI元素在html页面上的外观图像:

Image of how these UI elements look on the html page:

  1. 代码摘录,该摘录填写在下拉列表和文本框中:

  1. Code excerpt that fills in the drop-down list and the text-box:


//选择用户国家/地区和用户城市, //用户国家/地区下拉列表的ID为"id_country_name" //用户城市文本框的ID为id_city_name $(函数(){ $(#id_country_name").val(geoip_country_name()); $(#id_city_name").val(geoip_city()); //此时,用户的国家和城市值来自javascript调用 //现在是时候调用python代码来获取其他用户报告的国家和城市用户的数据值


// selecting users country and users city, // the id for users country drop-down list is "id_country_name" // the id for users city text-box is id_city_name $(function () { $("#id_country_name").val(geoip_country_name()); $("#id_city_name").val(geoip_city()); // at this point the users country and city values are in from the javascript call // now is the time to call python code to get the data values reported by other users for users country and city

    });
</script>

  • 用于查询数据库的示例python代码

  • Sample python code for querying the database

    def get_data_for_users_country_and_city(self):
        query = db.GqlQuery("SELECT * FROM UserReportedCity where county.country_name = country_name and city.city_name = city")
        data = query.fetch(10)
    

  • 我可能必须将这些项目包装在模板中,然后返回到html页面

    I have to probably package these items in a template and then return back to the html page

    template_values = {
           self.__TEMPLATE_DATA_FOR_USER: data 
        }
    
        #rendering the html page and passing the template_values
        self.response.out.write(template.render(self.__MAIN_HTML_PAGE, template_values))
    

    请注意,我尚未测试此python代码.

    Please note, i haven't tested this python code yet.

    使用javascript调用填写国家和城市的值后,我想调用python方法以获取用户国家和城市的数据并将其填充在您的城市"标签中.

    Once the values for country and city are filled in by the javascript call, I want to make a call to a python method to get the data for users country and city and populate it in the "Your City" tab.

    尝试了@Fabio Diniz和@Kevin P的建议

    Tried the suggestions given by @Fabio Diniz and @Kevin P

    以下是html和javascript代码:

    The following is the html and javascript code:

    <!-- script snippet to fill in users country and city value by making a calls to the geoip library -->  
    <script type="text/javascript">
        // selecting users country and users city, 
        // the id for users country drop-down list is "id_country_name"
        // the id for users city text-box is id_city_name
        $(function () {
            $("#id_country_name").val(geoip_country_name());
            $("#id_city_name").val(geoip_city()) 
         });
    
        $.post("/AjaxRequest/get_data_for_users_country_city", { 
            selected_country_name: document.getElementById('id_country_name').value, 
            selected_city_name: document.getElementById('id_city_name').value 
        },
        function(data) {
            alert("hello");
         }
        );
    
    </script>
    

    以下内容表明,对"/AjaxRequest/get_data_for_users_country_city"的请求应转到"AjaxRequest"类.

    The following indicates that the requests to "/AjaxRequest/get_data_for_users_country_city" should go to "AjaxRequest" class.

    def main():
      application = webapp.WSGIApplication([('/', MainPage),
                                          ('/UserReporting', UserReporting),
                                          ('/AjaxRequest/get_data_for_users_country_city', AjaxRequest )
                                          ],
                                         debug=False)
    
    run_wsgi_app(application)
    

    "AjaxRequest"类中​​的代码

    Code in "AjaxRequest" class

    from google.appengine.ext import db
    
    class AjaxRequest(webapp.RequestHandler):
    
      def post(self):
        user_reported_country_get = self.request.get('selected_country_name')
        user_reported_city_get = self.request.get('selected_city_name')
        data_for_users_country_city = self.get_data_for_users_country_and_city(user_reported_country_get, user_reported_city_get)
        self.response.out.write (data_for_users_country_city)
    

    问题:

    在调试模式下,我可以看到从javascript方法调用到"AjaxRequest","post"方法.问题是"user_reported_country_get"和"user_reported_city_get"没有由JavaScript代码指定的字符串值.

    In debug mode i can see that the call from javascript method making it to the "AjaxRequest", "post" method. The problem is that the "user_reported_country_get" and "user_reported_city_get" don’t have the string values given by the javascript code.

    根据@Matt Ball的建议,我在javascript调用中尝试了以下代码摘录

    Based on the suggestion given by @Matt Ball, I tried the following code excerpt in the javascript call

    <!-- script snippet to fill in users country and city value by making a calls to the geoip library -->  
    <script type="text/javascript">
        // selecting users country and users city, 
        // the id for users country drop-down list is "id_country_name"
        // the id for users city text-box is id_city_name
        $(function () {
            $("#id_country_name").val(geoip_country_name());
            $("#id_city_name").val(geoip_city()) 
         });
    
        $.post("/AjaxRequest/get_data_for_users_country_city", { 
            selected_country_name: $('#id_country_name').val(),
            selected_city_name: $('#id_city_name').val()            
        },
        function(data) {
            alert("hello");
         }
        );
    
    </script>
    

    国家/地区下拉列表和城市文本框的HTML代码摘录.这里国家/地区下拉列表的ID为"id_country_name",城市文本框为"id_city_name"

    HTML code excerpt for country drop-down list and city text-box. Here the id for the country drop-down list is "id_country_name" and the city text-box is "id_city_name"

    <div id="userDataForm">
     <form method="POST" action="/UserReporting"> 
       <table>
            <!-- Printing the forms for users country, city -->
            <tr><th><label for="id_country_name">Country name:</label></th><td><select       name="country_name" id="id_country_name">
    <option value="" selected="selected">---------</option>
    <option value="Afghanistan">Afghanistan</option>
    
    </select></td></tr>
            <tr><th><label for="id_city_name">City name:</label></th><td><input type="text" name="city_name" id="id_city_name" /></td></tr>     
       </table>
     </form>
    

    在python调试器中,"select_country_name"和"selected_city_name"的值仍然为空,如下图所示

    Inside the python debugger the values for "select_country_name" and "selected_city_name" are still empty as depicted by the following image

    返回的变量内的unicode值的图像>

    我认为出于某种原因,在调用python的过程中会发生在"id_country_name"和"id_city_name"值被填充之前的情况.因此,我没有尝试给出"id_country_name"和"id_city_name"的值,而是直接通过了geoip_country_name()和geoip_city()的值.这样就成功地将国家名称和城市名称传递回了python代码.

    I thought that for some reason during the call to python happens before the "id_country_name" and "id_city_name" values are filled in. So rather than trying to give the values of "id_country_name" and "id_city_name", i directly passed the values of geoip_country_name() and geoip_city(). This successfully passed the country name and city name back to python code.

    这是我尝试过的代码摘录.

    Here is the code excerpt i tried.

    <!-- script snippet to fill in users country and city value by making a calls to the geoip library -->  
    <script type="text/javascript">
        // selecting users country and users city, 
        // the id for users country drop-down list is "id_country_name"
        // the id for users city text-box is id_city_name
        $(function () {
            $("#id_country_name").val(geoip_country_name());
            $("#id_city_name").val(geoip_city()) 
         });
    
        $.post("/AjaxRequest", { 
            selected_country_name: geoip_country_name(),
            selected_city_name: geoip_city()            
        },
    
        function(data) {
            alert($('#id_country_name').val());
            alert($('#id_city_name').val())
         }
    
        );
    
    </script>
    

    根据@hyperslug提供的反馈,我将"$ .post("/AjaxRequest""部分移到了该函数中,该函数设置了用户国家/地区下拉列表和用户城市文本框.

    Based on the feedback given by @hyperslug, I moved the "$.post("/AjaxRequest" " piece inside the function which sets the users country drop-down list and users city text-box.

    此代码正确地将用户的国家和城市传递给python代码.

    This code correctly passes users country and city to python code.

    JavaScript代码摘录:

    Javascript code excerpt:

    <!-- script snippet to fill in users country and city value by making a calls to the geoip library -->  
    <script type="text/javascript">
        // selecting users country and users city, 
        // the id for users country drop-down list is "id_country_name"
        // the id for users city text-box is id_city_name
        $(function () {
    
            //finding the users country and city based on their IP.
            var $users_country = geoip_country_name()
            var $users_city = geoip_city()
    
            // setting the drop-down list of country and text-box of the city to users country and city resp
            $("#id_country_name").val($users_country);
            $("#id_city_name").val($users_city);
    
            //since we have users country and city, calling python class to get the data regarding users country and city combination 
            $.post("/AjaxRequest", { 
                selected_country_name: $users_country,
                selected_city_name: $users_city         
            })
    
         });
    
    </script>
    

    推荐答案

    您需要使用ajax. jQuery为此提供了一组不错的接口.

    You need to use ajax. jQuery gives you a nice set of interfaces for this.

    回复:OP编辑-尝试使用以下代码:

    Re: OP edit - try this code instead:

    $.post("/AjaxRequest/get_data_for_users_country_city", {
        selected_country_name: $('#id_country_name').val(),
        selected_city_name: $('#id_city_name').val()
    }, function(data) {
        alert("hello");
    });
    

    这篇关于从html页面上的javascript函数调用python方法以获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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