想要通过python返回的数据在html div中可用

2 投票
3 回答
2023 浏览
提问于 2025-04-16 15:56

A] 使用的技术:

1] Javascript

2] Jquery(目前使用的元素有Jquery标签和Jquery数据表)

3] Python

4] Google App Engine

B] 问题总结:

1] 我有一个javascript函数,它调用一个python类,并传入用户的城市和国家信息。

2] 这个python类会查询数据库,找到对应城市的信息,然后把这个对象返回给javascript。

3] 我在javascript中有一个提示框,可以看到对象成功打印出来。我使用了jquery标签,在标签里面有一个数据表。

在这里输入图片描述

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类获取到的数据能够在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

JavaScript无法直接处理Python对象,这就是你现在通过Ajax POST请求返回的内容。在你处理请求并返回数据之前,你需要把数据编码成一种格式(可以使用XML或JSON,正如fceruti提到的那样),这样JavaScript才能解码并使用这些数据。

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

看起来你在HTML里用了Django模板。这些内容是在服务器上处理的,所以你不能直接在代码里使用你返回的对象中的数据。你需要通过DOM(文档对象模型)来用jQuery进行修改。

你这里有一个ajax调用,这样你会收到一个xml格式的响应,你可以用jQuery来解析这个xml。

看起来你想要在表格中添加一行,或者用新数据替换掉某一行。如果是添加一行,你需要先获取表格

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)的内容替换成返回的新数据。

撰写回答