简体   繁体   中英

Calling a python method to fetch data, from a javascript function on the html page

Technologies being used

  • Google app engine
  • Django
  • Python
  • Jquery

Details of the code and code excerpts

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

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

在此输入图像描述

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


    // 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> 
  2. 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) 

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))

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

Question

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.

[EDIT#1]

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

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>

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)

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)

Problem:

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.

[EDIT#2]

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 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>

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

指示javascript返回的变量内的unicode值的图像

[EDIT#3]

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>

[EDIT#4]

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.

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

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>

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


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");
});

Create a page to act as your request handler for the country/city data then POST the country and city fields to the page using Ajax. Have the handler output the data you want based on the form fields. Use javascript to insert the returned data into your tab.

Example request handler:

class GeoData(webapp.RequestHandler):
    def post(self):    
        country = self.request.get('selected_country')
        city = self.request.get('selected_city')
        data = retrieve_my_data(country,city)            
        self.response.out.write(data)

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