2013-11-05 154 views
2

我用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',) 
+0

在Chrome中嘗試使用它,打開DevTools並確保在「sources」選項卡上單擊「未捕獲異常暫停」切換。這將幫助您本地化錯誤,並希望進入下一步調試。 –

+1

您正在創建'JSONResponse'實例,但不會從視圖中返回。你的JSON調用會得到任何'super(UploadedFileCreateView,self).form_valid'返回的結果 - 一個HTTP重定向,如果內存服務的話。 –

+0

請務必查看服務器返回的內容,並使用控制檯中的net選項卡。 – epascarello

回答

3

根據文檔here,該form_valid()方法需要返回JSON作爲HTTPResponse。相反,調用超類中的form_valid()將覆蓋前兩行上創建的響應。

編輯 -這是爲我工作:上述

def response_mimetype(request): 
    if "application/json" in request.META['HTTP_ACCEPT']: 
    return "application/json" 
    else: 
    return "text/plain" 

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(" ", "_"), 
     'type': "application/xml", 
     'size': self.object.file.size, 
     'delete_url': reverse('fileupload:upload-delete', 
     kwargs={'pk':self.object.id, 
     'proj_key':self.kwargs['proj_key']}), 
     'delete_type': "DELETE"}] 

    return HttpResponse(simplejson.dumps(data), content_type = response_mimetype(self.request)) 

在鏈接的代碼捆綁Ajax響應代碼作爲一個混合這將使該項目重用代碼的其他形式。

在Firefox插件中查看對Ajax調用的響應Firebug,Net選項卡或Chrome瀏覽器對應的幫助。這些將顯示請求和響應頭,確保正確的設置正在發送和返回。

+0

使用你的代碼,我得到'Empty file upload result'作爲javascript錯誤,儘管在控制檯中似乎沒有javascript異常。 – Plasma

+0

啊好的,你可以發佈你的HTML/JavaScript?然後,我很樂意正確調試代碼,;)。 –

+0

非常感謝!這裏是我的模板: https://github.com/PlasmaSheep/wseer/blob/master/wseeruploader/apps/fileupload/templates/fileupload/uploadedfile_form.html 而且在這裏引用的javascript: https://開頭github上。 com/PlasmaSheep/wseer/tree/master/wseeruploader/apps/fileupload/static/js – Plasma