如何将javascript变量转换为php变量?

时间:2014-10-17 18:45:55

标签: javascript php ajax variables

我是编程新手,我正在尝试制作一个可以在我的数据库中注册所选空间的程序。我想将js变量str转换为$ phpvar php变量。请帮帮我

$('#btnShowNew').click(function () {
            var str = [], item;
            $.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
                item = $(this).attr('title');                   
                str.push(item);                   
            });
            <?php 
            include "accounts/config.php";
            $phpvar='"+str+"';
            mysql_query("INSERT INTO sample (sample) VALUES ('".$phpvar."')"); 
            //echo $phpvar;

                  ?>; 
        })
    });

5 个答案:

答案 0 :(得分:2)

正如之前的发言者已经解释的那样,您需要考虑客户端运行代码和服务器端运行代码。

每当您想要在应用程序的这两个部分之间共享状态时,您需要一些通信机制。

客户 - &gt;服务器

为此,您需要发出HTTP请求。这可以是post或AJAX调用。对于后者,只需查看jquery.ajax,因为您显然已经在使用jQuery了。

$.post({
  "savesample.php",
  {myPostVar: str}
}).done(function() {
    alert("sample saved.");
});

当然,您需要一个服务器端脚本来处理此请求:

<?php
  $yourVar = $_POST["myPostVar"];
  // TODO use mysqli::escape_string or similar!!
  mysql_query("INSERT INTO sample (sample) VALUES ('".$yourVar."')");
?>

服务器 - &gt;客户端

这更容易。你当然可以再次使用ajax(在你的php文件上获取GET请求,这会生成一个像JSON一样的javascript兼容的输出)。

或者只是将您的变量写入内联脚本标记:

<script>
<![CDATA[
  var yourJsvar = '<?= $yourPhpVar ?>';
]]>
</script>

进一步阅读

由于您的php文件是各种滥用的开放门户,您应该使用一次性授权令牌来保护它。熟悉基本概念后,请继续阅读以下主题:

  • CORS
  • SQL注入
  • 经过身份验证的AJAX调用

答案 1 :(得分:1)

您希望POST到PHP侦听器。您不希望以这种方式在JS函数内部使用PHP标记。 PHP函数内部的PHP标记的唯一原因是,如果您从PHP获取数据到JS,而不是相反。

查看Jquery帖子了解更多信息。

答案 2 :(得分:0)

语言运行的顺序是PHP - &gt; HTML - &gt; CSS - &gt;的JavaScript。你不能从那个顺序倒退。

另一方面,您可以通过AJAX调用发送Javascript信息。 AJAX是一个可以与PHP通信的异步Javascript调用!

例如(使用JQuery)

$.ajax({
      url:"someurl",
      type:"POST or GET",
      data:{query:"SELECT * FROM table"}, //Any data to pass along? Like strings or data?
      datatype:"JSON", //This is the return type of the information you want if any
      success: successfulHandlerfunction()
      error: errorHandlerfunction()
});

这只是一些基本理由。您可以通过http://www.w3schools.com/ajax/

找到有关AJAX调用的更多信息

我希望这有帮助!

答案 3 :(得分:0)

这是不可能的,因为js代码是客户端而php是服务器端。您需要做的是向php脚本发出ajax请求,以便发送变量的数据。这是一个例子:

客户端(浏览器):

 $.ajax({url:"http://domain.com/accounts/config.php?variableToSend=variableValue",success:function(result){
      alert("Variable was successfully sent.");
    }});

服务器(Apache)的 的config.php

<?php
$varToSend = $_GET["variableToSend"]
//Do whatever you want with the variable
?>

答案 4 :(得分:0)

<强> JS

$('#btnShowNew').click(function () {

        var str = [], item;
        $.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {

             item = $(this).attr('title');                   
             str.push(item);     

        });

        $.ajax({

            type: "POST",
            url: "save.php",
            data: {items: str},
            success: function(responce) {

                  alert(responce);

            }

        });

});

创建save.php文件

<?php 

      include "accounts/config.php";

      $items = $_POST['items']; // Validation HERE!!!

      foreach ($items as $item) { 

          // Insert to DB

      }


      echo 'Saved';

?>
  1. 单独的语言=单独的文件。 (如果可以......
  2. 在PHP中始终检查用户输入。
  3. 使用PDO