Skip to content Skip to sidebar Skip to footer

Dynamic Jquery View In Django

my jquery looks like this: $('#id_start_date_list').change( function get_time() { var value = $(this).attr('value'); alert(value);

Solution 1:

To convert the results to json, use simplejson:

from django.utils import simplejson
defgetTime(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")

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
  }
});

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.

Post a Comment for "Dynamic Jquery View In Django"