【问题标题】:Want data returned by python to javascript to be accessible inside a html div希望 python 返回到 javascript 的数据可以在 html div 中访问
【发布时间】:2011-08-07 12:35:41
【问题描述】:

A] 正在使用的技术:

1] Javascript

2] Jquery(当前使用的元素是Jquery tab和Jquery datatable)

3] 蟒蛇

4] 谷歌应用引擎

B] 问题总结:

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

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>

我希望通过 javascript 函数从 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);
     }
 }    

【问题讨论】:

    标签: javascript python ajax google-app-engine


    【解决方案1】:

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

    【讨论】:

      【解决方案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 内容替换为返回的数据。

      【讨论】:

      • 根据您的回复,我修改了代码并提出了“EDIT#1”部分中指出的解决方案。能否请您查看代码并让我知道我是否犯了任何错误。
      • 很高兴你能成功。 EDIT1 对我来说看起来都不错。我会做的稍有不同,但这主要是一种风格选择:基本上我会分别创建每个 并使用 jQuery 将它们附加到行中,因为我觉得它会更具可读性和可维护性。
      【解决方案3】:

      您应该将您的对象编码为 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-18
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        • 2021-04-25
        • 1970-01-01
        • 2015-08-06
        • 1970-01-01
        相关资源
        最近更新 更多