希望python返回的数据可以在html div中访问javascript

时间:2011-04-17 23:51:19

标签: javascript python ajax google-app-engine

A]正在使用的技术:

1] Javascript

2] Jquery(当前使用的元素是Jquery选项卡和Jquery数据表)

3] Python

4] Google App引擎

B]问题摘要:

1]我有一个调用python类的javascript函数,并为用户提供城市和国家/地区值。

2]然后,python类查询数据库并找出数据库中的特定城市条目,并将对象返回给javascript。

3]我在javascript中有一个警告框,可以看到正在打印的对象。我正在使用jquery选项卡,在选项卡中我有一个数据表。

enter image description here

4]我希望javascript中获得的数据可以在jquery选项卡中使用,以便数据可以以数据格式打印

C]代码摘录:

1]调用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  
                               },
            function(data) {
                alert(data);
            }
        );

     });

</script>

2] jquery选项卡和jquery数据表的HTML代码。

<div id="userReportedData">     
<!-- Setting up the tabs to be shown in the html page, not the name of the tabs div is "tabs"
     this matches with the name defined the javascript setup for jquery tabs -->
 <div id="tabs">
    <!-- defining the tabs to be shown on the page -->
    <ul>
        <li><a href="#your_city">Your City</a></li>
    </ul>

    <div id="your_city">     
         <!-- Table containing the data to be printed--> 
         <table cellpadding="0" cellspacing="0" border="0" class="display" id="datatable_for_current_users">
         <thead>
            <tr>
                <th>Country</th>
                <th>City</th>
                <th>Reported at</th>
            </tr>
        </thead>
        <tbody>
            {%for status in data_for_users_city.statuses %}
                <tr class="gradeA">
                    <td>{{data_for_users_city.country.country_name}}</td>
                    <td>{{data_for_users_city.city_name}}</td>
                   <td>{{status.date_time }}</td>
                </tr>
            {%endfor%}  
         </tbody>
        </table>        
    </div>

我希望python类中的javascript函数获取的数据可以在tbody中访问。

注意:tbody中的for循环不起作用,一旦我正确加载了“data_for_users_city”的数据,那么我将测试它。

3]将数据发送到javascript的Python类:

class AjaxRequest(webapp.RequestHandler):

  #the string content of the template value 'all_data_from_datatabse'
  __TEMPLATE_ALL_DATA_FROM_DATABASE_FOR_USERS_CITY = 'data_for_users_city'

  def post(self):
    user_reported_country_get = self.sanitize_key_name( self.request.get("selected_country_name") )
    user_reported_city_get = self.sanitize_key_name( 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)

    template_values = {
        self.__TEMPLATE_ALL_DATA_FROM_DATABASE_FOR_USERS_CITY: data_for_users_country_city
    }

    self.response.out.write(data_for_users_country_city)

  def sanitize_key_name(self,key_name):
    string_key_name = unicodedata.normalize('NFKD', key_name).encode('ascii','ignore')
    return re.sub(r'\s', '', string_key_name.lower())

 def get_data_for_users_country_and_city(self,users_country,users_city):
    key_name_for_user_reported_city = users_country + ":" + users_city
    return UserReportedCity.get_by_key_name( key_name_for_user_reported_city )

[编辑#1]

有效的JavaScript解决方案

function LoadUsersDatatable(data) {
var tbody = $("#datatable_for_current_users > tbody").html(""); 
jsonData = jQuery.parseJSON(data);

for (var i = 0; i < jsonData.length; i++) 
{
        var citydata = jsonData[i]; 
        var rowText = "<tr class='gradeA'><td>" + citydata.city.country.country_name + "</td><td>" + citydata.city.city_name + "</td><td>" + citydata.status + "</td><td>" + citydata.date_time.ctime + "</td></tr>";
    $(rowText).appendTo(tbody);
     }
 }    

3 个答案:

答案 0 :(得分:2)

看起来你在HTML中使用了Django模板。这都是服务器端解析的,因此您将无法使用内联代码中返回的对象中的数据。相反,您需要使用jQuery通过DOM进行更改。

你在那里有一个ajax调用,所以你将在xml中获得一个响应,你可以使用jquery进行解析。

看起来您想要向表中添加另一行,或者用新数据替换其中一行。如果添加一行,您需要获取表格

function(data) {
    var newRow = $('<tr class="gradeA"></tr>');

    //you can use $('attributename', data) to access each attribute
    // in the returned data object

    // build tds with the data, like I've done in the line above for the tr
    // then append them to newRow, using .append()

    // then we can just append the new row to the table
    $('#your_city').find('tbody').append(newRow);
}

如果你想替换一行,你可以做类似的事情,但先删除旧行,或者使用jQuery找到你想要更改内容的行,并用返回的数据替换td内容。

答案 1 :(得分:0)

您应该将对象编码为JSON或XML(但我更喜欢JSON)。您可以在python中手动执行,也可以使用jsonpickle等库。然后在你的javascript上你可以用安全的方式解析那个字符串:

var jsonObj = JSON.parse(data);

然后当你想要访问它非常容易的东西时。假设你有这个JSON

{
"students": [
        {"name": "mark", "picture": "/a.jpg"},
        {"name" : "steve", "picture": "/b.jpg"}
    ],
"class": "Biology"
}

您可以访问以下数据:

> document.println(jsonObj.students[0].name)
mark

> document.println(jsonObj.class)
Biology

答案 2 :(得分:0)

Javascript无法对python对象做任何事情,这就是现在通过Ajax POST返回的内容。在使用请求处理程序返回任何内容之前,您需要以一种可以使用javascript解码的方式对数据进行编码(使用fceruti提到的XML或JSON)。