首页 > 解决方案 > Uncaught TypeError: Object(...) is not a function at HTMLButtonElement.addHandleSubmit

问题描述

不确定我是否理解为什么会显示此错误。getCityData("username", where) 在 HandleSubmit.js 中注释掉时,错误似乎消失了。我已经检查了相关的答案,但似乎并不相关。

JS: Uncaught TypeError: object is not a function (onclick)

提前致谢

错误

HandleSubmit.js:16 Uncaught TypeError: Object(...) is not a function
    at HTMLButtonElement.addHandleSubmit (HandleSubmit.js:16)

获取数据.js

import axios from 'axios';

 async function getCityData(username, city) {
    const url=  "http://api.geonames.org/searchJSON?q=",
    completeURL = `${url}${city}&username=${username}`
    console.log(completeURL)

    try {
        let data = await axios.get(completeURL).then((response) => {
            console.log(response.data);
            console.log(response.status);
            console.log(response.statusText);
            console.log(response.headers);
            console.log(response.config);
            data = response;
          });
          return data;

    }
    catch(error) {
        console.log("error", error);
      }



}

export default  {
    getCityData
}

处理提交.js

import getCityData from "./getData"



function addHandleSubmit (e) {
    e.preventDefault()
    const where = document.getElementById("where").value
    const when = document.getElementById("when").value

    // if (where=='' || when=='') {
    //     alert('Please make sure you have add a Where and When')
    // }
    console.log(`To ${where} departing ${when}`)


   getCityData("username", where)




}
export default {
    addHandleSubmit
}


index.js

import "./styles/styles.scss";
import addHandle from "./js/HandleSubmit";
import getCityData from "./js/getData";


document.getElementById("add-trip").addEventListener('click', addHandle.addHandleSubmit)

export {
    addHandle,
    getCityData

}

索引.html

                 <div class="add-trip-form">
                        <form>
                            <label for="where"> where</label>
                            <input type="text" id="where"> 
                            <label for="when"> When</label>
                            <input type="date" id="when">
                            <button class="add-trip-class" id="add-trip"> Add Trip</button>
                        </form>
                    </div>

标签: javascriptaxios

解决方案


在 HandleSubmit.js 中,你应该像这样导入:

import { getCityData } from "./getData"

否则,您将getCityData作为对象导入,而不是像函数一样导入。这就是为什么你得到那个错误


推荐阅读