将变量值从JS传递给PHP [英] Pass variable value from JS to PHP

查看:79
本文介绍了将变量值从JS传递给PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将一个值从JS传递给PHP时遇到了问题,因此它可以用作PHP函数的参数。一旦链接被点击,JS功能将由onclick事件触发。这里是JS + HTML代码:

I have a problem in passing a value from JS to PHP so that it can be used as a parameter for a PHP function. The JS function will be trigger by onclick event once the link was clicked. Here is the JS + HTML code:

<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 (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非常陌生,所以请原谅我的愚蠢。

Thank you for the one who can help me.. I am very new to PHP and JS so please forgive my stupidity.

推荐答案

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

You pass data from the browser to your server. Javascript is a language for manipulating the browser. PHP is your server side language.

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

You can pass data in a get or post request such as "mypage.php?Username=john"

您需要的是一种表单,以便您可以与用户交互

What you want is a form so that you can interact with the user

<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>

这篇关于将变量值从JS传递给PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆