我用jQuery使用Django上傳文件使用Ajax。但是,在文件上傳後(文件確實上傳正確;數據庫已更新,並且位於服務器上),javascript會返回SyntaxError: Unexpected token <
錯誤。Django:SyntaxError:意外的令牌<
我不知道這是javascript中的錯誤還是django中的錯誤;我看到的其他問題似乎建議確保信息確實採用JSON格式,但似乎在我的情況下格式正確。我不明白爲什麼會有錯誤,因爲一切看起來都很好。我的日誌中沒有錯誤。
如果我只能看到更有幫助的錯誤消息,我會更容易解決問題。
這裏是我的views.py:
def response_mimetype(request):
if "application/json" in request.META['HTTP_ACCEPT']:
return "application/json"
else:
return "text/plain"
class JSONResponse(HttpResponse):
"""JSON response class."""
def __init__(self,obj='',json_opts={},mimetype="application/json",*args,**kwargs):
content = simplejson.dumps(obj,**json_opts)
a = super(JSONResponse,self).__init__(content,mimetype,*args,**kwargs)
class UploadedFileCreateView(CreateView):
model = UploadedFile
form_class = UploadedFileForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.project_id = self.kwargs['proj_key']
self.object.save()
f = self.request.FILES.get('file')
data = [{
'name': self.object.name(),
'url': "/uploads/xmlfiles/" + self.object.name().replace(" ", "_"),
'delete_url': reverse('fileupload:upload-delete',
kwargs={'pk':self.object.id,
'proj_key':self.kwargs['proj_key']}),
'delete_type': "DELETE"}]
response = JSONResponse(data, {}, response_mimetype(self.request))
response['Content-Disposition'] = 'inline; filename=files.json'
return super(UploadedFileCreateView, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(UploadedFileCreateView, self).get_context_data(**kwargs)
context['files'] = UploadedFile.objects.all()
context['proj'] = int(self.kwargs["proj_key"])
return context
這是我的models.py:
class UploadedFile(models.Model):
"""This represents a file that has been uploaded to the server."""
STATE_UPLOADED = 0
STATE_ANNOTATED = 1
STATE_PROCESSING = 2
STATE_PROCESSED = 4
STATES = (
(STATE_UPLOADED, "Uploaded"),
(STATE_ANNOTATED, "Annotated"),
(STATE_PROCESSING, "Processing"),
(STATE_PROCESSED, "Processed"),
)
status = models.SmallIntegerField(choices=STATES,
default=0, blank=True, null=True)
file = models.FileField(upload_to=settings.XML_ROOT)
project = models.ForeignKey(Project)
def __unicode__(self):
return self.file.name
def name(self):
return os.path.basename(self.file.name)
def save(self, *args, **kwargs):
if not self.status:
self.status = self.STATE_UPLOADED
super(UploadedFile, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
os.remove(self.file.path)
self.file.delete(False)
super(UploadedFile, self).delete(*args, **kwargs)
def get_absolute_url(self):
return u'/upload/projects/%d' % self.id
class UploadedFileForm(ModelForm):
class Meta:
model = UploadedFile
exclude = ('project',)
在Chrome中嘗試使用它,打開DevTools並確保在「sources」選項卡上單擊「未捕獲異常暫停」切換。這將幫助您本地化錯誤,並希望進入下一步調試。 –
您正在創建'JSONResponse'實例,但不會從視圖中返回。你的JSON調用會得到任何'super(UploadedFileCreateView,self).form_valid'返回的結果 - 一個HTTP重定向,如果內存服務的話。 –
請務必查看服務器返回的內容,並使用控制檯中的net選項卡。 – epascarello