2016-08-16 51 views
-1

我想使用jquery获取发布数据。我有implemen使用jquery获取发布数据

HTML表单

 <form id="login_form" action="userPref.php" method="post" > 

     <div hidden id="error" style="color:red; text-align:center;" > <p> user not found </p> </div> 
     <div class="form-group"> 
      <label for="usrname"><span class="glyphicon glyphicon-user "></span> User Id</label> 
      <input type="text" value="" class="form-control" required="required" id="usrname" name="usrname" placeholder="Enter User Id" > 
     </div> 

      <button type="submit" id="login" class="btn btn-success btn-block"><span class="glyphicon glyphicon-off"></span> Login</button> 
     </form> 

在userPref.php我使用PHP来获得数据,但其实我是想使用jquery

var userid = <?php echo $_POST["usrname"] ?>; 

我也试图访问表单数据使用jquery,但我无法访问数据。请帮帮我。

+1

有很多教程和例子。其中一个http://www.htmlgoodies.com/tutorials/forms/article.php/3895776或只是谷歌,你会发现他们的吨。 – ProgrammerV5

+0

[jQuery Ajax POST示例与PHP]可能重复(http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php) –

回答

0

POST数据是服务器端处理的数据。而JavaScript/jQuery在客户端。所以你不可以使用JavaScript/jQuery来读取发布数据。

但好办法是

var post_data= <?php echo json_encode(!empty($_POST) $_POST : array());?>; 

现在你可以访问$ _ POST [ '用户名'];

alert(post_data.username); 

因此您可以通过此方式访问所有发布的数据。

+0

var userid = <?php echo $ _POST [“usrname “]?>; 我已经实现的这段代码工作正常。但在我的情况下,我不能使用PHP文件。我只需要使用js文件。这个小php脚本不能在html或js文件中运行。 –

+0

所以,我只需要用js来做。 –

+0

是的,不幸的是,你必须使用js来做到这一点。 –

0

检查:

<html> 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
    </head> 
    <body> 
     <div id="results"></div> 

     <form action="" method="post"> 
      <input typte="text" name="uName" /> <input typte="password" 
       name="passKey" /> <input type="submit" /> 
     </form> 
     <script type="text/javascript"> 
       $('form').submit(function(e){ 
        if(this.uName.value != ''){ 
         alert(this.uName.value); 
        } 
        if(this.passKey.value != ''){ 
         alert(this.passKey.value); 
        } 
       }); 
       </script> 
    </body> 

    </html> 
+0

如何在发布此表单的页面上获取这些值? –

0

在服务器端,你需要这样的事:

<input type="text" value="" class="form-control" required="required" id="usrname" name="usrname" placeholder="Enter User Id"<?php echo isset($_POST["usrname"]) ? ' value="'.$_POST["usrname"].'"' : ''; ?> > 

,然后你可以使用jQuery使用它,像这样:

$("#usrname").val()