【问题标题】:How to validate the input field before redirecting to the next page如何在重定向到下一页之前验证输入字段
【发布时间】:2019-06-26 17:03:25
【问题描述】:

这是我的第一个 html 代码:

 <form action = "indextable.html" method="GET"  >  
 <p><input name = "ManagerId" class="form-control" id="ManagerId" type 
 ="text" autocomplete="off" onkeyup="alphanumOnly(this)" maxlength="8"  
 placeholder="ManagerId"></input></p>
 <p> <input type="submit" onclick ='return getRepoCount();' 
  value="submit">Submit</body></p>
 </form>      
<script>
 function alphanumOnly(input){
    var regex = /[^a-zA-Z0-9]/gi;
    input.value = input.value.replace(regex, "");
    }
function getRepoCount(){
    var empid = document.getElementById("ManagerId").value;
    alert(empid);
    $.ajax({
    url:'http://localhost:8088/JirasTrackingApp/reporter/
    Reportees/ReporteeList/'+ empid,
    type:'GET',
    dataType: 'json',
    success: function(result){
        alert('hi');
        return true;
    },
    error:function(result){
    alert("Please enter an valid input");
        return false;

    }
   });
 }
</script>

在这里我无法进行 ajax 调用。当我运行程序时,它会显示 empid 警报。但是成功和错误的警报不会显示。就像它不只是进行 ajax 调用一样.请告知我哪里出错了。

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    将您的输入类型提交更改为按钮,像这样

    <input type="button" onclick ='return getRepoCount();' value="submit">
    

    单击提交按钮后,表单会在触发警报功能之前重新加载,这就是您没有收到响应警报的原因。

    或者您可以使用 onSubmit 事件触发事件,例如

    <form action="indextable.html" method="GET"  onsubmit="getRepoCount()"> 
    

    这不允许页面重新加载,除非js代码执行为真。如果你不想重新加载它,你应该返回 false。

    【讨论】:

    • 非常感谢,这正是我真正想要的。
    【解决方案2】:

    尝试使用它。还要确保 api 返回正确的 json。

    <script>
    function alphanumOnly(input){
     var regex = /[^a-zA-Z0-9]/gi;
    input.value = input.value.replace(regex, "");
    }
    function getRepoCount(){
    var empid = document.getElementById("ManagerId").value;
    alert(empid);
    $.ajax({
    url:'http://localhost:8088/JirasTrackingApp/reporter/
    Reportees/ReporteeList/'+ empid,
    type:'GET',
    dataType: 'json',
    success: function(result){
        alert('hi');
        return true;
    },
    error:function(result){
        alert("Please enter an valid input");
        return false;
    
    },
     complete: function () {
        // Handle the complete event
        alert("ajax completed " + "Your Data");
     }
    });
    return false;
    }
    </script>
    

    这是我从 API 得到的响应:

        [{"UserId":"at12345","count":0,"Name":"Amras  Taj"}, 
        {"UserId":"AR12345","count":0,"Name":"Anaagh R"}, 
        {"UserId":"MS12345","count":4,"Name":"Madhan S"}]
    

    【讨论】:

    • 我已经检查了 api,它正在根据需要返回数据
    • 为 firefox 安装 firebug 插件(如果尚未安装),并检查 AJAX 回调。您将能够看到响应,以及它是否收到成功的 (200 OK) 响应。您还可以在完整的回调中添加另一个 alert(),它肯定会被调用。
    • 也有可能是utf char的问题,请检查一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2016-07-17
    相关资源
    最近更新 更多