动态JQuery视图在django [英] dynamic JQuery view in django

查看:158
本文介绍了动态JQuery视图在django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的jquery如下所示:

my jquery looks like this:

$('#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看起来像这样:

my view.py looks like this:

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页面如下所示:

my html page looks like this:

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对象中。

As you can see i am getting the value from the select box and i am performing operations on the database and retreiving values and storing it in the json object.

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

There are two parts that i am totally blind. First is the json object, where i am not sure whether the results are getting stored in the response_var object. The second is that, i am not sure how to get values from a json object onto the new list of "start_time_list"

详细说明:在json对象初始化中完成任何错误。我试图打印respose_var,但似乎没有打印在控制台上。我使用正确的语法吗?并且有人可以告诉我如何在view.py

In detail: have i have done anything wrong in the json object initialisation. I have tried to print the respose_var, but it seems not to be printed on the console. Am i using the right syntax? and can someone tell me how to view the values stored in the json object in the view.py

中查看存储在json对象中的值。以类似的方式,我如何在jQuery方面执行操作,从json对象中提取值,以及如何通过示例代码和可能的解决方案将json对象的值分配到列表框中。

In the similar way, how do i perform operations on the jquery side, to extract values from a json object and how to assign the values of a json object onto a list box by means of sample code and possible solutions.

推荐答案

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

To convert the results to json, use 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 。这是包含服务器响应的变量。所以,要访问结果数组的第一个元素(例如),您可以:

To access the json object in your javascript, take a look at your ajax request. The success callback is being passed a parameter, data in this case. That is the variable containing the server response. So, to access the first element of the resultant array (for instance), you could:

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提供了很多方法,如 html 追加。值得一看 doc 。因此,如果要为选择标签构建一组选项,则应该使用循环的javascript 遍历结果集,jQuery / code>方法或类似的,构造选项(这可以实现串联字符串或创建DOM元素,我认为这是最好的解决方案,因为它表现更好),并使用其中一种方法将它们插入到html中前面提到过。

Lastly, to modify the html, jQuery provides plenty of methods, such as html or append. It's worth taking a look at the doc. So if you want to build a collection of options for a select tag, you should iterate over the result set using the javascript for loop, jQuery each method or similar, construct the options (this can be accomplished either concatenating strings or creating DOM elements, which I think is the best solution, as it performs better) and insert them in the html with one of the methods previously mentioned.

这篇关于动态JQuery视图在django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆