【问题标题】:Using plain Javascript to check Username Uniqueness使用纯 Javascript 检查用户名唯一性
【发布时间】:2023-03-04 16:28:02
【问题描述】:

目标:

我想检查后端数据库是否存在用户在“帐户配置”网页中输入的用户名,并且我希望它检查用户何时离开用户名字段.我不想有一个动态的选项下拉列表。

建议的流程:

  1. 用户在 html 表单的用户名输入字段中输入他们想要的用户名。 (假设他们在用户名字段中输入了“Mary”)
  2. 用户选项卡或鼠标移动到下一个字段(出生日期),这会触发用户名字段上的验证事件。
  3. 验证事件通过 URL 向我的服务器发送请求:“https://localhost/jsfetch?qrynm=unqusrnm&Mary”
  4. 后端数据库确定“Mary”不是唯一的用户名,并自动从生成器(SQL 序列)中附加一个整数,并将“Mary1”返回到用户仍然打开的网页。
  5. 用户现在看到他们的用户名已更改为“Mary1”。他们接受更改并继续,或者,他们更改用户名字段中的名称,然后再次切换到下一个字段,该过程再次从第 3 步开始。

我通过研究发现有四种方法可以做到这一点,(AJAX、Fetch、RubyOnRails、数据验证)我都无法为我工作。

所有这些答案似乎都“错过了”我正在尝试做的事情。我可以编写服务器端代码以将响应发送回请求。我需要 Javascript 方面的帮助才能完成这项工作。任何帮助将不胜感激。显然有一种更简单的方法可以做到这一点,而不是我在下面使用的代码,使用“数据验证”,但我也无法让它工作。这是页面的完整代码。这些尝试都不起作用。他们中的大多数会调用我的后端服务器,但没有一个会显示文本:

<!doctype html>
<html>
<head>
<meta name="viewport" http-equiv="content-type" content="width=device-width, initial-scale=1.0">
<title>My Page</title>
<style>
</style>
</head>
<body>

<form action="/savenewacccfg" method="POST">
<h1>Testin the onblur Event. Try number 86</h1>
<div id="username_warning"></div>
<input class="input-field" type="text" name="username" id="username" maxlength="50" placeholder="Login ID" onblur="CheckUnique('usrname', this.value)" required>
<input class="input-field" type="password" name="new_acc_pwd" id="new_acc_pwd" maxlength="50" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" placeholder="Password: Caps, Smalls, Numbers, 8 chars or more" required>
</form>

<script>

<!-- This works in the browser URL box.  -->
<!-- It returns the only the text "Mary87" (for example):  https://localhost/jsfetch?qrynm=unqusrnm&usrnm=Mary -->
<!-- Replace this URL with one that you know will return a short piece of text -->

<!-- This calls the server, but will not display the "Mary87" -->
function CheckUnique5(chkwut, thsusrnm) {
  const xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("username_warning").innerHTML = 
        '<span style="font-style:italic;color:red;">Username changed to ' + this.responseText + ' !</span>';
    }
  };
  xhttp.open("GET", 'https://localhost/jsfetch?qrynm=unqusrnm&usrnm=' + thsusrnm);
  xhttp.send();
}

<!-- This calls the server, but will not display the "Mary87" -->
function CheckUnique(chkwut, thsusrnm) {
  if (chkwut == 'usrname') {
    let fetchRes = fetch('https://localhost/jsfetch?qrynm=unqusrnm&usrnm=' + thsusrnm);
    fetchRes.then(res => res.text())
    .then(d => {document.getElementById("username_warning").innerHTML = 
      '<span style="font-style:italic;color:red;">Username changed to ' + d + ' !</span>'})    
  }
}
  
<!-- This calls the server, but will not display the "Mary87" -->
function CheckUnique3(chkwut, thsusrnm) {
  if (chkwut == 'usrname') {
    fetch('https://localhost/jsfetch?qrynm=unqusrnm&usrnm=' + thsusrnm)
    .then(x => x.text())
    .then(y => document.getElementById("username_warning").innerHTML = '<span style="font-style:italic;color:red;">Username changed to ' + y + ' !</span>');    
  }
}

<!-- This calls the server, but will not display the "Mary87" -->
async function CheckUnique2(chkwut, thsusrnm) {
  if (chkwut == 'usrname') {
    let response = await fetch('https://localhost/jsfetch?qrynm=unqusrnm&usrnm=' + thsusrnm);
    let data = await response.text();
    document.getElementById("username_warning").innerHTML = '<span style="font-style:italic;color:red;">Username changed to ' + data + ' !</span>';    
  }
}

<!-- This displays the username handed in -->
function CheckUnique1(chkwut, thsusrnm) {
  if (chkwut == 'usrname') {
  document.getElementById("username_warning").innerHTML = '<span style="font-style:italic;color:red;">Username changed to ' + thsusrnm + ' !</span>';
  }
}

</script>

</body>
</html>

【问题讨论】:

  • 您应该遇到语法错误。如果函数未声明async,则不能使用await
  • return await res.text() 结束函数,所以下一行不会被执行。
  • 事件监听器的返回值不用于任何事情,那么你希望return await res.text(); 做什么呢?
  • 为什么是usr_nm_ctrl.value 而不是this.value
  • 您的问题在于await 在这里developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch 研究带有 await 函数(不是调用 fetch 函数)的 fetch 示例

标签: javascript


【解决方案1】:

问题已解决:

原来它与我从未听说过的“CORS”有关。当行为不端的页面打开时,我通过按 F12 键发现了这一点。 (勇敢或铬,不记得哪个)。通过研究浏览器 F12 窗口中显示的确切错误消息,我了解到我需要在我的 API 方法中打开我的 HEAD 和 OPTIONS 方法,然后在我的响应中包含以下 OPTIONS:

// 必须满足 CORS

AResponse.Headers.Add('Access-Control-Allow-Methods', 'OPTIONS,GET');
AResponse.Headers.Add('Access-Control-Allow-Headers', 'Content-Type');
AResponse.Headers.Add('Access-Control-Allow-Origin', '*');

这是我要工作的 Javascript:

function CheckUnique(chkwut, thsval) {
  if (chkwut == 'usrname') {
    var myRequest = new Request('https://localhost/jsfetch?qrynm=unqusrnm&usrnm=' + thsval);
    fetch(myRequest).then(function(response) {
      return response.text().then(function(text) {
        document.getElementById("username_warning").innerHTML = '<span style="font-style:italic;color:red;">Login ID changed to: ' + text + + '</span>';
      });
    });
  
  }
}

现在我从我的服务器收到此响应:

登录 ID 更改为:Mary125NaN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 2014-03-28
    • 1970-01-01
    • 2011-04-25
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多