我有一个弹出窗口模式显示在页面加载中,其中包含以下形式:
<form class="enterForm">
<label class="modalFields" id="userName" style="display: none;">
<span>user Number :</span>
<input type="text" name="userNum" placeholder="User Number" required/>
</label>
</form>
<label>
<span> </span>
<input type="submit" value="Submit" class="submitButton">
<input type="hidden" id="hiddenInput">
</label>
在用户提交表单时,我希望通过AJAX调用来访问某个API,该调用返回一个如下所示的JSON:
{
"results":[
{
"person":{
"firstName":"John",
"lastName":"Smith"
},
"userNumber":"12345"
}
]
}
如果userNumber与用户提交的值匹配,那么我想更新导航栏以说出该人的名字。在流程方面我希望它:用户类型中的用户类型 - &gt;提交表格 - &gt; AJAX调用命中API - &gt;检查用户输入是否与JSON中的userNumber值匹配 - &gt;如果匹配,则选择firstName值并在导航栏中更新它。我怎么能实现这个目标呢?
答案 0 :(得分:2)
考虑到你知道如何进行AJAX调用并且你正在使用API,集成jQuery来促进这个事情不应该太难(如果是的话,我在解决方案之后包含了额外的信息)。 / p>
<强>的JavaScript 强>
//On form submit
$('#enterForm').submit(function(){
var userNum = $('[name="userNum"]').val();
//AJAX call to your API
$.ajax({
url: 'myAPICall.php',
/* data: {userNumber: userNum}, //If necessary */
success: function(data) {
// Note: this code is only executed when the AJAX call is successful.
if(data.results.userNumber == userNum){
$('#navBarFirstName').text(data.results.person.firstName);
}
},
error: function (err) {
//If the AJAX call fails, this will be executed.
console.error(err);
}
dataType: 'JSON'
});
return false; //Prevents the page refresh if an action is already set on the form.
});
使用jQuery将函数(事件侦听器)绑定到表单的submit
事件。
触发submit
事件时,该函数运行:
.text()
使用您的JSON响应的 firstName 属性更新导航栏内容。 您可以通过在HTML页面中包含脚本来集成jQuery。您可以download it或使用CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">
/* Don't put your code in here it won't be parsed */
</script>
<!-- the following tag could also be <script src="link/to/your/script.js"></script> -->
<script>
/* Your actual script */
</script>
请确保将此行放在包含上面编写的脚本的实际javascript文件之前,否则jQuery不会被初始化并且脚本无法正常工作。