Jquery 如何从HTML调用API?
我试图通过HTML调用我的API来检查数据库,这样当我单击按钮时,它将调用API,然后用数据库检查正确的结果并相应地输出。到目前为止,我还不完全确定如何做到这一点,并尝试过这一点Jquery 如何从HTML调用API?,jquery,html,ajax,Jquery,Html,Ajax,我试图通过HTML调用我的API来检查数据库,这样当我单击按钮时,它将调用API,然后用数据库检查正确的结果并相应地输出。到目前为止,我还不完全确定如何做到这一点,并尝试过这一点 <div id="login"> <h1>Welcome Back!</h1> <form action="http://localhost:3000/api/login" method="post"> <div c
<div id="login">
<h1>Welcome Back!</h1>
<form action="http://localhost:3000/api/login" method="post">
<div class="field-wrap">
<label>
Username<span class="req">*</span>
</label>
<input type="userID"required autocomplete="off"/>
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="Password"required autocomplete="off"/>
</div>
<p><button class="button button-block">Log In</button></p>
</form>
</div>
我曾经尝试过使用AJAX,但它一直重定向回主页,所以我决定尝试放置,看看它是否会检查数据库,但它一直给出错误的输出,尽管它应该是正确的,因为它在数据库中。如果你需要更多的细节,一定要告诉我。感谢您的帮助!请注意,这不是为了验证而只是为了试验。首先,您应该添加一个事件侦听器,以便在提交事件侦听器时进行侦听
document.getElementById("loginForm").addEventListener('submit', login);
function login() {
$.ajax(settings).done(function (response) {
console.log(response);
}
}
不过。确保传递给api的数据经过正确的处理,以便进行验证。
假设api需要一些作为参数传递给函数的数据,inout字段必须具有名称属性值作为代码中的相应参数。
如果你的代码如下所示:
function login(string user, string userpswd) {
// Code here...
}
那么您的HTML应该是:
<form id="myForm">
<input type="text" name="user" placeholder="Username" />
<input type="password" name="userpswd" requiered="required" />
</form>
例如。在表单中指定一个id,以及单个控件的名称和id
<form method="POST" action="http://localhost:3000/api/login" id="loginform">
<input type="userID" id="userID" name="userID" required autocomplete="off"/>
.....
<input type="submit" id="submit" value="Log In">
</form>
编辑:
请参阅以了解表单提交回调函数
我写的与
$("#formid").submit(function( event ) {
alert( "Handler for .submit() called." );
event.preventDefault();
});
实际上向服务器发出http post请求
这是一个简写的ajax调用,相当于下面的
$.ajax({
type: "POST", <---Note this
url: url,
data: data,
success: success,
dataType: dataType
});
$p.点击。。。?否。将单击处理程序绑定到按钮。如果您想使用Ajax,那么您不希望表单提交,因此您需要取消按钮的默认行为或向按钮添加type=button。我知道这个问题上没有jQuery标记,但OP显然使用jQuery,所以为什么不使用$loginForm.onsubmit。。。?您还需要调用event.preventDefault.Hi我可以知道什么是functionevent,如果$post。。。是所有ajax请求以及input type=userIDbecause都需要的,因为我在w3wschools.com中找不到它,所以这是否取决于您的字段在任何类型的词中?这意味着什么数据类型不需要声明,或者是否有默认值?只是好奇,但是点击功能是否也可以实现,或者对于表单提交之类的东西来说更复杂?
$("#formid").submit(function( event ) {
alert( "Handler for .submit() called." );
event.preventDefault();
});
$.ajax({
type: "POST", <---Note this
url: url,
data: data,
success: success,
dataType: dataType
});