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

问题描述

我有一个php和javascript代码文件。我想将一个php变量设置为javascript函数的结果,该函数将php变量作为参数。例如:

I have a file of php and javascript code. I want to set a php variable to be the result of a javascript function which takes a php variable as a parameter. For example:

$parameter = "this is a php variable";
$phpVar = echo "foo(" . parameter . ");";

我知道你不能做= echo,还有另外一种方法吗?

I know you cannot do a "= echo", is there another way I can do this?

谢谢

推荐答案

你不能直接这样做,因为JavaScript在客户端运行,PHP在服务器端执行。

You can't directly do that, since JavaScript runs on the client-side and PHP gets executed on the server-side.

您需要先执行JavaScript,然后通过FORM将结果发送到服务器或者AJAX调用。

You would need to execute the JavaScript first and then send the result to the server via a FORM or AJAX call.

这可能是这样的:

PHP

$parameter = "this is a php variable";
echo "var myval = foo(" . parameter . ");";

JavaScript

JavaScript

var myval = foo("this is a php variable"); // generated by PHP

$.ajax({
  type: 'POST',
  url: 'yourphpfile.php',
  data: {'variable': myval},
});

接收PHP(yourphpfile.php)

Receiving PHP (yourphpfile.php)

$myval = $_POST['variable'];
// do something

这篇关于将javascript变量传递给php代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 10:15