【问题标题】:dynamic JQuery view in djangodjango中的动态JQuery视图
【发布时间】:2012-08-05 07:22:21
【问题描述】:

我的 jquery 看起来像这样:

$('#id_start_date_list').change(
        function get_time()
        {
            var value = $(this).attr('value');
            alert(value);
            var request = $.ajax({
                url: "/getTime/",
                type: "GET",
                data: {start_date : value},         
                dataType: "json",
                success: function(data) {               
                //Popluate combo here by unpacking the json
        }
        });

        });

我的 view.py 看起来像这样:

def getTime(request):
    if request.method == "GET":
        date_val =  request.GET.get('start_date')                        
        format = '%Y-%m-%d' 
        sd = datetime.datetime.strptime(date_val, format)
        sql_qw = MeasurementTest.objects.filter(start_date = sd)        
        results = [{'start_time': str(date.start_time), 'id_start_time':date.start_time} for date in sql_qw]
        print results                   
        *****json_serializer = serializers.get_serializer("json")()
        response_var=  json_serializer.serialize(results, ensure_ascii=False, indent=2, use_natural_keys=True)*****

    return HttpResponse(response_var, mimetype="application/json")

我的 html 页面如下所示:

html>
<head>
    <title>date Comparison</title>

<script src="http://code.jquery.com/jquery-latest.js"></script>    
</head>
<body>   
    {% if form.errors %}
        <p style="color: red;">
            Please correct the error{{ form.errors|pluralize }} below.
        </p>
    {% endif %}
    <form action="/example/" method="post" align= "center">{% csrf_token %}
         <table align = "center">
         <tr>
            <th><label for="start_date_list">Date 1:</label></th>
            <th>        {{ form.start_date_list }}          </th>               
        </tr>                  
        <tr>

        <th><label for="start_time_list">time:</label></th>
        <th><select name="start_time_list" id="start_time_list"></th>
            <option></option>           
        </select>
        <th></th>

        <div id = "log"></div>
        </tr>

        <tr align = "center"><th><input type="submit" value="Submit"></th></tr> 
         </table>         
    </form>
</body>
</html>

如您所见,我正在从选择框中获取值,并且正在对数据库执行操作并检索值并将其存储在 json 对象中。

有两个部分我完全失明。 首先是 json 对象,我不确定结果是否存储在 response_var 对象中。 第二个是,我不确定如何从 json 对象获取值到“start_time_list”的新列表中

详细说明:我在 json 对象初始化中做错了什么吗?我试图打印 respose_var,但它似乎没有打印在控制台上。我使用正确的语法吗?有人可以告诉我如何在 view.py 中查看存储在 json 对象中的值

同理,我如何在jquery端进行操作,从json对象中提取值,以及如何通过示例代码和可能的解决方案将json对象的值赋给列表框。

【问题讨论】:

    标签: javascript jquery python django json


    【解决方案1】:

    要将结果转换为 json,请使用 simplejson:

    from django.utils import simplejson
    def getTime(request):
    if request.method == "GET":
        date_val =  request.GET.get('start_date')                        
        format = '%Y-%m-%d' 
        sd = datetime.datetime.strptime(date_val, format)
        sql_qw = MeasurementTest.objects.filter(start_date = sd)        
        results = [{'start_time': str(date.start_time), 'id_start_time':date.start_time} for date in sql_qw]
        print results
        response_var = simplejson.dumps(results)
    
    return HttpResponse(response_var, mimetype="application/json")
    

    要访问您的 javascript 中的 json 对象,请查看您的 ajax 请求。成功回调正在传递一个参数,在这种情况下为data。那是包含服务器响应的变量。因此,要访问结果数组的第一个元素(例如),您可以:

    var request = $.ajax({
      url: "/getTime/",
      type: "GET",
      data: {start_date : value},         
      dataType: "json",
      success: function(data) {               
        //Popluate combo here by unpacking the json
        data[0];  // This is the first element of the array sent by the server
      }
    });
    

    最后,修改html,jQuery提供了很多方法,如htmlappenddoc 值得一看。因此,如果您想为选择标签构建选项集合,您应该使用 javascript for 循环、jQuery each 方法或类似方法遍历结果集,构建选项(这可以通过连接字符串或创建 DOM 元素,我认为这是最好的解决方案,因为它性能更好)并使用前面提到的方法之一将它们插入到 html 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-26
      • 2015-04-24
      • 1970-01-01
      • 2012-04-21
      • 2016-09-30
      • 2020-05-24
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多