我曾经写过一个将字符串传递到api的代码。这种st必须满足某种模式,然后,如果满足该模式,则必须通过单击按钮来存储此字符串来调用api。
将字符串传递到数据库
<link rel="stylesheet" type="text/css" href="css/style.css">
<style>
body{
background: url("images/background.jpg");
background-size: cover;
}
<div class="data" >
<h1>SignUp Here</h1>
<form method = "POST" >
<p>Username</p>
<input type="text" name="citycode" placeholder="Enter citycode" id="citycode" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 6 or more characters">
<p>Password</p>
<input type="code2" name="countrycode" placeholder="Enter countrycode" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 6 or more characters" id="countrycode">
<button type="submit" name="submit" onclick="myFunction()">Submit</button> </br> </br> </br>
</form>
</div>
</body>
<script type="text/javascript">
function myFunction() {
var citycode, countrycode;
city = document.getElementById('citycode').value;
country = document.getElementById('countrycode').value;
var xhttp = new XMLHttpRequest();
var url = "https://my api url";
var sending = JSON.stringify({
"citycode": city,
"countrycode": country
});
xhttp.open("POST", url, true);
xhttp.send(sending);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log("status success");
alert(xhttp.responseText);
}
};
//}
}
</script>
</html>
当我单击“提交”按钮时,它正在检查并显示模式匹配结果,但是在有效和无效情况下都传递数据。
任何人都可以帮助我解决此问题。
答案 0 :(得分:1)
请勿在“提交”按钮的myFunction()
属性中调用onclick
。表单验证是在onclick
函数返回后提交表单时进行的。在表单的onsubmit
属性中进行操作。
<form method="POST" onsubmit="myFunction(); return false;">
您还应该使用return false;
,否则即使您已经使用AJAX发送了数据,表单也将正常提交。