首页 > 解决方案 > 未捕获的 ReferenceError:未定义常量

问题描述

在我看来,我有这行 html:<div id="ajax" data-value="photos_path"></div>

然后在我的js中我这样做:

import 'uppy/dist/uppy.min.css'
import '@uppy/core/dist/style.min.css'
import '@uppy/webcam/dist/style.min.css'

import {
 Core,
 Dashboard,
 Webcam,
 AwsS3,
} from 'uppy'

function fileUpload(fileInput) {
 const hiddenInput = document.querySelector('.upload-data'),
 const post_url = document.getElementById('ajax').getAttribute('data-value'),
 const s3_url = document.getElementById('s3').getAttribute('data-value')

 const uppy = Core({
  autoProceed: true,
  allowMultipleUploads: true,
  restrictions: {
    maxFileSize: 10000000,
    maxNumberOfFiles: 10,
    allowedFileTypes: ['image/jpeg', 'image/png']
  }
})
.use(Dashboard, {
  inline: true,
  target: '#file-uppy',
  trigger: '.upload-file',
  hideUploadButton: true,
  replaceTargetContent: false,
  showProgressDetails: true,
  width: 1200,
  height: 400,
})
.use(Webcam, {
  target: Dashboard,
})
.use(AwsS3, {
  companionUrl: s3_url,
})

uppy.on('upload-success', (file, response) => {
 const uploadedFileData = {
  id: file.meta['key'].match(/^cache\/(.+)/)[1], // object key without prefix
  storage: 'cache',
   metadata: {
    size: file.size,
    filename: file.name,
    mime_type: file.type,
   }
  }
  $.ajax({
   type: "POST", 
   url: post_url,
   data: { 
    photo: {
     image: uploadedFileData
    }
   }
  })
 })
}

export default fileUpload

然而由于某种原因,js没有编译。我得到这个错误:Uncaught ReferenceError: post_url is not defined。在我看来它是定义的?事实上,我对另一个数据值做同样的事情。<div id="s3" data-value="docs"></div>在视图中和s3 = document.getElementById('s3').getAttribute('data-value')。这非常完美。

为什么一个有效而另一个无效?

标签: javascriptajax

解决方案


改变这个:

post_url = document.getElementById('ajax').getAttribute('data-value')

对此:

const post_url = document.getElementById('ajax').getAttribute('data-value')

与 javascript 中的 python 和 ruby​​ 不同,您需要使用关键字(const、let 或 var)来声明变量或常量。


推荐阅读