Используемые технологии
- Движок приложения Google
- Django
- Python
- Jquery
Подробная информация окод и выдержки из кода
У меня есть раскрывающийся список (страна) и текстовое поле (город) {раскрывающийся список и текстовое поле генерируются django-формой}, которые получают автоматическизаполняется библиотекой GeoIp
Изображение того, как эти элементы пользовательского интерфейса выглядят на html-странице:
![enter image description here](https://i.stack.imgur.com/jBOsS.png)
Отрывок кода, который заполняетраскрывающийся список и текстовое поле:
// выбор страны пользователя и города пользователя, // идентификатор страны для раскрывающегося списка «id_country_name» // идентификатор города пользователятекстовое поле: id_city_name $ (function () {$ ("# id_country_name"). val (geoip_country_name ()); $ ("# id_city_name"). val (geoip_city ()); // на данный момент страна пользователя игородские значения взяты из вызова javascript // сейчас время вызывать код python для получения значений данных, сообщаемых другими пользователями для пользователей cстрана и город
});
</script>
Пример кода Python для запросов к базе данных
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-страницу
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.
Вопрос
Как только значения для страны и городазаполнены вызовом javascript, я хочу вызвать метод python, чтобы получить данные о стране и городе пользователя и заполнить их на вкладке «Ваш город».
[EDIT #1]
Попробовал предложения @Fabio Diniz и @Kevin P
Ниже приведены html и javascript код:
<!-- 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".
def main():
application = webapp.WSGIApplication([('/', MainPage),
('/UserReporting', UserReporting),
('/AjaxRequest/get_data_for_users_country_city', AjaxRequest )
],
debug=False)
run_wsgi_app(application)
Код в классе "AjaxRequest"
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.
[EDIT # 2]
На основеПо предложению @Matt Ball я попробовал следующую выдержку из кода в 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_country_name», а текстовое поле города - «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» по-прежнему пусто, как показано на следующем изображении
![Image indicating unicode values inside the variables returned by javascript](https://i.stack.imgur.com/mu4zB.png)
[EDIT # 3]
Я думал, что по какой-то причинево время вызова python происходит до того, как значения "id_country_name" и "id_city_name" будут заполнены. Поэтому вместо того, чтобы пытаться дать значения "id_country_name" и "id_city_name", я напрямую передал значения geoip_country_name () и geoip_city (),Это успешно передало название страны и название города обратно к коду Python.
Вот отрывок кода, который я пробовал.
<!-- 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>
[РЕДАКТИРОВАТЬ # 4]
Основываясь на отзывах, предоставленных @hyperslug, я переместил фрагмент «$ .post (" / AjaxRequest "« внутрьфункция, которая устанавливает раскрывающийся список страны пользователя и текстовое поле города пользователя.
Этот код правильно передает страну и город пользователя в код Python.
Отрывок кода Javascript:
<!-- 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>