我终于明白了。我已将过程分为多个部分。然后我调用 AJAX 来访问它。
我的urls.py 文件:
from django.conf.urls import url
from .views import tag, check_tagid, scan_tag
urlpatterns = [
url(r'^tag/', tag, name="tag"),
url(r'^check_tagid/', check_tagid, name="check_tagid"),
url(r'^scan_tag/', scan_tag, name="scan_tag"),
]
我的views.py 文件:
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .models import Student
import serial
def check_tagid(request):
"""Check if scanned tag id is already associated or not"""
tagid = request.GET.get('tagid', None)
if Student.objects.filter(tag_id__iexact=tagid).exists():
data = {
'is_taken': Student.objects.filter(tag_id__iexact=tagid).exists(),
'student': Student.objects.get(tag_id=tagid).name
}
else:
data = {
'is_taken': Student.objects.filter(tag_id__iexact=tagid).exists(),
}
return JsonResponse(data)
def scan_tag(request):
"""Function to check if tag is scanned or not"""
if request.is_ajax():
## Init RFID reader
data = serial.Serial(
port='/dev/ttyUSB1',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
context = {'tagid': data.read(12).decode("utf-8")}
return JsonResponse(context)
else:
return HttpResponse("This route only handles AJAX requests")
def tag(request):
return render(request, 'students/tag.html', {})
我的tag.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<center><h1><div id="tag_id">Scanning for tag</div></h1></center>
<div id="if_exists"></div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.get("/scan_tag/", function(data) {
console.log(data.tagid);
var x = document.createElement("INPUT");
x.setAttribute("id", "tag_id_in");
x.setAttribute("type", "hidden");
x.setAttribute("value", data.tagid);
document.body.appendChild(x);
// check tag
tagid = $("#tag_id_in").val();
console.log(tagid);
$.ajax({
type: "GET",
url: "{% url 'check_tagid' %}",
data: {
'tagid': tagid
},
success: function(data) {
if (data.is_taken) {
document.getElementById('tag_id').innerHTML = "Welcome "+data.student;
} else {
document.getElementById('tag_id').innerHTML = "No student with this tag id found";
}
}
});
});
});
</script>
</body>
</html>
所有这些现在都按预期工作。
所以,/tag/ 是主要入口点。现在在tag.html 中,我在/scan_tag/ 上使用jQuery get 方法。它将返回 RFID 标签号。然后我在/check_tagid/ 上调用 AJAX,它的真/假取决于学生是否在数据库中。