简体   繁体   English

将表单输入与JSON对象进行比较

[英]Comparing form input to JSON object

I have a popup modal that displays on page load that has the following form in it: 我有一个弹出模式,显示在页面加载中,具有以下形式:

<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>&nbsp;</span>  
    <input type="submit" value="Submit" class="submitButton">
    <input type="hidden" id="hiddenInput">
</label> 

And on user submission of the form, I want to hit a certain API via an AJAX call, which returns a JSON that looks like: 在用户提交表单时,我想通过AJAX调用来打入某个API,该调用返回的JSON如下所示:

{  
   "results":[  
      {  
         "person":{  
            "firstName":"John",
            "lastName":"Smith"
         },
         "userNumber":"12345"
      }
   ]
}

If the userNumber matches the value that the user submitted, I then want to update the nav bar to say the person's first name. 如果userNumber与用户提交的值匹配,那么我想更新导航栏以说出该人的名字。 In terms of process flow I want it to go: user types in user number -> submits form -> AJAX call hits API -> checks to see if user input matches userNumber value in JSON --> if match, selects the firstName value and updates it in the nav bar. 就流程而言,我希望它能够执行:用户类型输入用户编号->提交表单-> AJAX调用命中API->检查用户输入是否与JSON中的userNumber值匹配->如果匹配,则选择firstName值并在导航栏中更新它。 How could I go about achieving this? 我该如何实现这一目标?

Considering you know how to do AJAX calls and you're using an API, integrating jQuery to facilitate the thing shouldn't be too hard (if it is, I included additional information after the solution). 考虑到您知道如何进行AJAX调用,并且您正在使用API​​,因此集成jQuery来简化操作应该不会太难(如果可以的话,在解决方案之后我还会提供其他信息)。

Solution

JavaScript 的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.
});

Explanation 说明

You use jQuery to bind a function (event listener) to the submit event of your form. 您使用jQuery将函数(事件侦听器)绑定到表单的submit事件。

When the submit event is triggered, the function runs: 触发submit事件时,该函数运行:

  • It gets the value of your DOMElement with the name attribute " userNum " 它使用名称属性“ userNum ”获取DOMElement的值。
  • It makes an AJAX call to your API (with/without the userNum value, you choose if you want to check that on the server side or not) 它将对您的API进行AJAX调用(有/无userNum值,您可以选择是否要在服务器端进行检查)
  • On success, (when the call is done successfully), it updates the navbar content using .text() with the firstName attribute of your JSON response. 成功时(成功完成调用后),它将使用.text()和JSON响应的firstName属性更新导航栏内容。

Including jQuery 包括jQuery

You can integrate jQuery by including the script within your HTML page. 您可以通过将脚本包含在HTML页面中来集成jQuery。 You can either download it or use a CDN : 您可以下载它或使用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>

Make sure to put this line before your actual javascript file containing the script written above, otherwise jQuery won't be initialized and the script won't work. 请确保将此行放在包含上述脚本的实际javascript文件之前,否则jQuery将不会初始化并且该脚本将无法工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM