我正在尝试基于rest framework API JSON文件创建一个简单的HTML搜索输入。到目前为止,我设法从JSON文件中获取数据。在控制台日志中,我想要的数据就在那里,但是当我在搜索字段中搜索它时,它会给我这个错误:
GET http://127.0.0.1:8000/nameList?term=a 404 (Not Found)
我尝试将其转换为字符串,但仍然没有区别。
这是我的代码: HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
</head>
<body>
<br>
<input id="name_search_tags" type="text" placeholder="Search...">
</body>
<script>
$.getJSON("list/?format=json", function (json) {
console.log(json);
$.each(json, function(key, val) {
var nameList = [];
var employee_name = val.employee_name;
nameList.push(employee_name.toUpperCase());
var string = nameList.toString();
console.log(employee_name);
console.log(nameList);
});
$("#name_search_tags").autocomplete({source: 'nameList'});
});
</script>
</html>
model.py
from django.db import models
# Create your models here.
class MyModel(models.Model):
employee_name = models.CharField(max_length=100)
def __str__(self):
return self.employee_name
serializer.py
from rest_framework import serializers
from .models import *
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
#fields = ('field 1','field 2')
fields = '__all__'
view.py
from django.shortcuts import render
from .models import *
from .forms import *
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import *
class MyModelList(APIView):
def get(self, request):
#get all objects in model
modelList = MyModel.objects.all()
#convert to JSON #multiple objects in model
serializers = MyModelSerializer(modelList, many=True)
#return the serialize JSON data
return Response(serializers.data)
url.py
from django.conf.urls import url
from django.contrib import admin
from search.views import *
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', search, name='search'),
url(r'^list/', MyModelList.as_view(), name='list_view'),
]
urlpatterns = format_suffix_patterns(urlpatterns)
JSON
[
{
"id": 1,
"employee_name": "Rajiv"
},
{
"id": 2,
"employee_name": "Izzat"
},
{
"id": 3,
"employee_name": "Nagendra"
},
{
"id": 4,
"employee_name": "Shawn"
},
{
"id": 5,
"employee_name": "Jason"
}
]
感谢大家的帮助。感谢
答案 0 :(得分:0)
我不熟悉自动完成库,但我认为nameList
应该是保存JSON源的变量。它也需要在each
循环之前初始化,现在它在退出each
循环后立即被清除。