你如何将javascript变量输入到php脚本中?

时间:2014-04-03 22:48:25

标签: javascript php jquery html

我正在尝试获取一个调用带有输入的php函数的函数。

javascript函数(picNum是一个整数):

function hello(picNum) {
   var pictureNumber = picNum;

   var phpFunc = "<?php 
      include 'otherfile.php';
      otherFileFunc(" + pictureNumber + ") //This is where the problem is, the input(pictureNumber) wont go through
   ?>";
   echo phpFunc;
}

otherfile.php

<?php
   function otherFileFunc($i) {
      $final = $i + 1;
      echo $final;
   }
?>

这段代码几乎说如果你做onclick =“hello(1)”那么输出或phpFunc应该是2,因为你在otherfile.php中添加一个,但无论输入输出总是1所以我'我猜测我刚刚标记的输入是不会经历的。

不要告诉我它没有工作,因为它做到了。 如果我把一个整数而不是“+ pictureNumber +”它完美地工作!

感谢任何帮助:)

2 个答案:

答案 0 :(得分:1)

不幸的是,你无法通过javascript调用php。

Php从服务器运行,javascript在客户端运行(通常,例外是node.js.但是即使在node.js的实例中,也没有使用php,因为javascript已经取代了它的功能)

如果您需要javascript&#34;请拨打&#34;一个服务器函数,您需要查看ajax请求,以便服务器可以运行一个函数并将其返回给客户端。

答案 1 :(得分:1)

你必须使用Ajax兄弟:

使用Javascript:

 function hello(picNum) {
   var pictureNumber = picNum;
   $.ajax({
     url: "otherfile.php",
     data: {"picNum":pictureNumber},
     type:'post',
     dataType:'json',
     success: function(output_string){
       PictureNumber = output_string['picturenumber'];
       alert(PictureNumber);
     }
   });
 }

PHP otherfile.php:

$picNum = $_POST['picNum'];
function otherFileFunc($pic){
  $final = $pic + 1;
  return $final;
}
$outputnumber = function($picNum);
$array = ('picturenumber' => $outputnumber);
echo json_encode($array);

注意:未经测试

编辑,测试:

的javascript:

function hello(picNum) {
   var pictureNumber = picNum;
   $.ajax({
     url: "otherfile.php",
     data: {"picNum":pictureNumber},
     type:'post',
     dataType:'json',
     success: function(output_string){
       pictureNumber = output_string['picturenumber'];
       alert(pictureNumber);
     }
   });
 }
hello(1); //sample

PHP otherfile.php:

$picNum = $_POST['picNum'];
$picNum = 1;
function otherFileFunc($pic){
  $final = $pic + 1;
  return $final;
}
$outputnumber = otherFileFunc($picNum);
$array = array('picturenumber' => $outputnumber);

echo json_encode($array);
相关问题