简体   繁体   English

自定义输入框行为

[英]Custom input box behaviour

I have some simple HTML : 我有一些简单的HTML:

First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">

What I wish to do is submit this form using JQuery and store what is entered in a database. 我想做的是使用JQuery提交此表单并将所输入的内容存储在数据库中。 The page, without refreshing would then update to show: 无需刷新的页面将更新为显示:

<p>Thanks for submitting $fname + $lname</p>

I would also like for a cookie to be created so that if the same user is to visit the site, it will always show this message rather than force them to see the input form multiple times. 我还希望创建一个cookie,以便如果同一用户访问该站点,它将始终显示此消息,而不是强迫他们多次查看输入表单。

What is the best way for me to do this? 我这样做的最佳方法是什么? How can I do this using JQuery? 如何使用JQuery做到这一点? Is there a better alternative? 有更好的选择吗? It is simple to do using PHP, but I would like it to be as interactive as possible and my example is just a very simple representation of what I will have :). 使用PHP做到这一点很简单,但是我希望它尽可能地具有交互性,而我的示例只是对我将要拥有的东西的非常简单的表示:)。

You can use jQuery Ajax. 您可以使用jQuery Ajax。

It is very simple: First of all you need to add jQuery file in your head tag like this: 这很简单:首先,您需要像这样在head标签中添加jQuery文件:

<!-- Add jquery library -->
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
     $(document).ready(function(){ 
         $("#btnSubmit").click(function(){
             var fname = $("#fname").val();
             var lname = $("#lname").val();
             $.ajax({
                 url : "updateDb.php", // php file where you write your mysql query to store value
                 type : "POST", // POSTmethod
                 data : {"fistname":fname,"lastname":lname},
                 success : function(n){
                      // after success you can alert popup here
                      // also set you cookies here
                      // I have also function for set  cookie through javascript  
                      setCookie("username",fname,30);
                 } 
             });
         });
     });

     function setCookie(c_name,value,exdays)
     {
      var exdate=new Date();
      exdate.setDate(exdate.getDate() + exdays);
      var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
      document.cookie=c_name + "=" + c_value;
     }
</script>
</head>

<!-- Now your HTML code -->
First name: <input type="text" name="fname" id="fname"><br>
Last name: <input type="text" name="lname" id="lname"><br>
<input type="button" value="Submit" id="btnSubmit">

<!-- Note : if you use input type=submit then page must load.so you need to remove that and use only button -->

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

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