javascript JS导入失败,尽管遵循了类似问题的所有前面的答案

x33g5p2x  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(186)

我知道类似的问题已经问了很多,但他们的答案都没有对我起作用。我有两个js文件:
/js/ajax.js

export function ajax(url, content, callback, errorCallback) {
  const httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = function () {
    try {
      if (httpRequest.readyState === XMLHttpRequest.DONE) {
        const response = JSON.parse(httpRequest.responseText);
        if (httpRequest.status === 200) {
          callback(response);
        } else {
          errorCallback(response);
        }
      }
    } catch (e) {
      console.log(httpRequest.responseText);
    }
  };
  httpRequest.open("POST", url);
  httpRequest.setRequestHeader("Content-Type", "application/json");
  httpRequest.overrideMimeType("application/json");
  httpRequest.send(JSON.stringify(content));
}

register.js

import { ajax } from "./js/ajax.js";

const usernameInput = document.querySelector("#register #username");
const passwordInput1 = document.querySelector("#register #password1");
const passwordInput2 = document.querySelector("#register #password2");
passwordInput2.addEventListener("keydown", identicalPassword, false);

function registerFail(response) {
  usernameInput.value = "";
  passwordInput1.value = "";
  passwordInput2.value = "";
  alert(response.error_message);
}

function registerSuccess() {
  alert("Success, please log in");
  window.location.assign("login.html");
}

function tryRegister() {
  ajax(
    "php/register.php",
    {
      username: usernameInput.value,
      password1: passwordInput1.value,
      password2: passwordInput2.value,
    },
    registerSuccess,
    registerFail
  );
}

它们都导入到register.html中:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Register</title>
  </head>
  <body>
//[...]
    <script src="/js/ajax.js" type="module"></script>
    <script src="register.js"></script>
  </body>
</html>

这会导致错误[Error] SyntaxError: Unexpected token '{'. import call expects one or two arguments.,据这里的其他答案告诉我,* 不应该 * 发生:我通过名称导入,一个函数,它是从一个包含在html中的模块脚本中以正确的路径导出的。我做错了什么?

ruarlubt

ruarlubt1#

我认为是不允许在浏览器中使用ES6关键字,如果你想使用'import',你需要在脚本标签中添加'module',例如:

<script src="/js/ajax.js" type="module"></script>
 <script src="register.js" type="module"></script>

相关问题