私の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オブジェクトに保存しています。
私が完全に盲目である2つの部分があります。1つ目はjsonオブジェクトで、結果がresponse_varオブジェクトに格納されているかどうかわかりません。2つ目は、jsonオブジェクトから「start_time_list」の新しいリストに値を取得する方法がわからないことです。
詳細:jsonオブジェクトの初期化で何か間違ったことをしましたか?respose_varを印刷しようとしましたが、コンソールに印刷されていないようです。私は正しい構文を使用していますか?そして誰かがview.pyのjsonオブジェクトに保存されている値を表示する方法を教えてもらえますか
同様の方法で、jquery側で操作を実行して、jsonオブジェクトから値を抽出する方法と、サンプルコードと可能な解決策を使用してjsonオブジェクトの値をリストボックスに割り当てる方法を説明します。