将变量值从JS传递给PHP

时间:2011-12-29 00:58:11

标签: php javascript jquery mysql html

我在将值从JS传递给PHP时遇到问题,因此它可以用作PHP函数的参数。单击链接后,onclick事件将触发JS函数。这是JS + HTML代码:

<script type="text/javascript">
   function insertIntoDb() {
      $.GET OR POST("insert.php");
      return false;
   }
</script>

<a href="#" onclick="insertIntoDb();">INSERT MY USERNAME</a>

PHP(insert.php):

<?php
    session_start();

    function insert($username){
        $username = mysql_real_escape_string($username);
        $query = mysql_query("INSERT INTO List(Username) VALUES('$username')") or die(mysql_error());
    }

    if(isset($_POST['Username'])){
        insert($_POST['Username']);
    }
?>

感谢能帮助我的人..我是PHP和JS的新手,所以请原谅我的愚蠢。

2 个答案:

答案 0 :(得分:1)

的index.html

<script src="http://code.jquery.com/jquery-latest.min.js" type='text/javascript'></script>
<script>
   $(document).ready(function(){ 
       $("#insert").click(function(event){
           $.post('insert.php',{username:$(this).html()});
       })
   });
</script>
<a href='javascript:void(0);' id='insert'>Username</a>

insert.php

<?php
function insert($username){
    $conn = mysql_connect("host","user","passwd");
    if($conn){
        $username =  mysql_real_escape_string($_POST['username']);
        $result = mysql_query("INSERT INTO test.user(username) VALUES('".$username."')") or die(mysql_error());
        mysql_close($conn);
    }
}
if(isset($_POST['username'])){
    insert($_POST['username']);
}
?>

答案 1 :(得分:0)

您将数据从浏览器传递到服务器。 Javascript是一种用于操纵浏览器的语言。 PHP是您的服务器端语言。

您可以在get或post请求中传递数据,例如“mypage.php?Username = john”

您想要的是一个表单,以便您可以与用户进行交互

<script type="text/javascript">
    function insertIntoDb() {
      document.getElementById("myform").submit();
      //or if you want to use jquery and ajax
      $.post("insert.php", $("#myform").serialize());
      return false;
    }
</script>

<form id="myform" method="post" action="insert.php">
    <a href="#" onclick="insertIntoDb();">INSERT MY USERNAME</a>
    <input type="text" name="Username"></input>
</form>
相关问题