2016-08-16 87 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()