将值从PHP传递给JavaScript [重复]

时间:2021-01-08 17:04:23

This question already has an answer here:

这个问题在这里已有答案:

I have PHP code as in the following.

我有PHP代码,如下所示。

<?php
    echo "<SCRIPT LANGUAGE='javascript'>add dd_Employee('".$id1."','".$fname1."',".$sal1.");</SCRIPT>";
    echo "<SCRIPT LANGUAGE='javascript'>add dd_Employee('".$id2."','".$fname2."',".$sal2.");</SCRIPT>";
    ....

?>
...

And my JavaScript code contains

我的JavaScript代码包含

var details=new Array();

function addEmployee(id,fname,salary){
    var temp=new Array(id,fname,salary);
    details[details.length]=temp;
    alert(temp);
}

function displayEmployee(){
    for (var i=0;i<details.length;i++)
        var temp_details=details[i];

    //Display the id,name,sal
    var id=temp_details[0];
    var name=temp_details[1];
    var sal=temp_details[2];

    alert(id);
    alert(name);
    alert(sal);
}

Now the problem is whatever assigned by the PHP will visble only in AddEmployee. Which means it is working fine. But inside displayEmployee the value assigned by PHP will not work. Is there any flaw in my logic?

现在问题是PHP分配的任何东西只会在AddEmployee中出现。这意味着它工作正常。但是在displayEmployee中,PHP分配的值不起作用。我的逻辑有什么缺陷吗?

4 个解决方案

#1


Just populate your global data structure directly rather than passing it through a JavaScript function. You are likely running into a variable scope problem since you are allocating memory in addEmployee.

只是直接填充您的全局数据结构,而不是通过JavaScript函数传递它。由于您在addEmployee中分配内存,因此可能会遇到可变范围问题。

Example:

<?php
print "details[details.length] = new Array('$id1', '$name1', '$salary1');\n";
?>

#2


It looks like you're missing some curly braces in your for loop. Right now, you've got a 1-line for loop that does nothing but assign a value to your temp variable, which is re-declared on every iteration. I can't remember what the scope rules are for JavaScript in this situation, but it's generally bad practice to do this (if it's intentional). Try something like this for your displayEmployee() method.

看起来你在for循环中缺少一些花括号。现在,你有一个1行的for循环除了为你的temp变量赋值,它在每次迭代时重新声明。我不记得在这种情况下JavaScript的范围规则是什么,但这通常是不好的做法(如果它是故意的)。尝试使用displayEmployee()方法。

function displayEmployee(){
    for(var i=0; i<details.length; i++) {

        var temp_details = details[i];

        //Display the id, name, and sal.
        var id = temp_details[0];
        var name = temp_details[1];
        var sal = temp_details[2];

        alert(id);
        alert(name);
        alert(sal);
    }
}

That should fix your immediate problem. If you have control over all of your code, I'd recommend turning the employee data into an object so it's more manageable. To do this, you should use this PHP code:

这应该可以解决你的问题。如果您可以控制所有代码,我建议将员工数据转换为对象,以便更易于管理。为此,您应该使用以下PHP代码:

<?php
    echo '<script>
              addEmployee('.json_encode(array(
                  'id'     => 'id1',
                  'name'   => 'fname1',
                  'salary' => 1024,
              )).');
              addEmployee('.json_encode(array(
                  'id'     => 'id2',
                  'name'   => 'fname2',
                  'salary' => 2048,
              )).');
         </script>';
?>

And then alter your JavaScript code to look like this:

然后将您的JavaScript代码更改为如下所示:

var details = [];

function addEmployee(employeeObj){
    details[details.length] = employeeObj;

    alert(employeeObj);
}
function displayEmployee(){
    for(var i=0; i<details.length; i++) {
        alert(details[i].id);
        alert(details[i].name);
        alert(details[i].salary);
    }
}

I haven't tested this code, but it should run.

我没有测试过这段代码,但它应该运行。

#3


You have an error in your JavaScript call generated by PHP

您在PHP生成的JavaScript调用中有错误

echo "<SCRIPT LANGUAGE='javascript'>add dd_Employee('".$id1."','".$fname1."',".$sal1.");</SCRIPT>";

should be

echo "<SCRIPT LANGUAGE='javascript'>addEmployee('".$id1."','".$fname1."',".$sal1.");</SCRIPT>";

And if you want to change it to OOP?

如果你想把它改成OOP?

<?php
    $employeeList[] = array('sdf3434', 'Bob', 123.34);
    $employeeList[] = array('wer335dg', 'Joe', 223);
?>
<html>
    <head>
        <script>
            function Employees() {
                this.list = new Array();
            }
            Employees.prototype.add = function (id, fname, sal) {
                this.list.push(new Array(id, fname, sal));
            };
            Employees.prototype.display = function () {
                for(var i=0, t = this.list.length;i<t;i++) {
                    var emp = this.list[i];
                    alert(emp[0]);
                    alert(emp[1]);
                    alert(emp[2]);
                }
            };
            var employees = new Employees();
            <?php
                foreach ($employeeList as $employee) {
                    list($id, $fname, $sal) = $employee;
                    printf("employees.add('%s', '%s', %f);\n", $id, $fname, $sal);
                }
           ?>
        </script>
    </head>
    <body>
        <a href="#" onclick="employees.display();">click</a>
    </body>
</html>

#4


The blog post Value Exchange from JavaScript/HTML page to PHP and from PHP page to JavaScript may be helpful for some.

从JavaScript / HTML页面到PHP以及从PHP页面到JavaScript的博客文章Value Exchange可能对某些人有所帮助。

#1


Just populate your global data structure directly rather than passing it through a JavaScript function. You are likely running into a variable scope problem since you are allocating memory in addEmployee.

只是直接填充您的全局数据结构,而不是通过JavaScript函数传递它。由于您在addEmployee中分配内存,因此可能会遇到可变范围问题。

Example:

<?php
print "details[details.length] = new Array('$id1', '$name1', '$salary1');\n";
?>

#2


It looks like you're missing some curly braces in your for loop. Right now, you've got a 1-line for loop that does nothing but assign a value to your temp variable, which is re-declared on every iteration. I can't remember what the scope rules are for JavaScript in this situation, but it's generally bad practice to do this (if it's intentional). Try something like this for your displayEmployee() method.

看起来你在for循环中缺少一些花括号。现在,你有一个1行的for循环除了为你的temp变量赋值,它在每次迭代时重新声明。我不记得在这种情况下JavaScript的范围规则是什么,但这通常是不好的做法(如果它是故意的)。尝试使用displayEmployee()方法。

function displayEmployee(){
    for(var i=0; i<details.length; i++) {

        var temp_details = details[i];

        //Display the id, name, and sal.
        var id = temp_details[0];
        var name = temp_details[1];
        var sal = temp_details[2];

        alert(id);
        alert(name);
        alert(sal);
    }
}

That should fix your immediate problem. If you have control over all of your code, I'd recommend turning the employee data into an object so it's more manageable. To do this, you should use this PHP code:

这应该可以解决你的问题。如果您可以控制所有代码,我建议将员工数据转换为对象,以便更易于管理。为此,您应该使用以下PHP代码:

<?php
    echo '<script>
              addEmployee('.json_encode(array(
                  'id'     => 'id1',
                  'name'   => 'fname1',
                  'salary' => 1024,
              )).');
              addEmployee('.json_encode(array(
                  'id'     => 'id2',
                  'name'   => 'fname2',
                  'salary' => 2048,
              )).');
         </script>';
?>

And then alter your JavaScript code to look like this:

然后将您的JavaScript代码更改为如下所示:

var details = [];

function addEmployee(employeeObj){
    details[details.length] = employeeObj;

    alert(employeeObj);
}
function displayEmployee(){
    for(var i=0; i<details.length; i++) {
        alert(details[i].id);
        alert(details[i].name);
        alert(details[i].salary);
    }
}

I haven't tested this code, but it should run.

我没有测试过这段代码,但它应该运行。

#3


You have an error in your JavaScript call generated by PHP

您在PHP生成的JavaScript调用中有错误

echo "<SCRIPT LANGUAGE='javascript'>add dd_Employee('".$id1."','".$fname1."',".$sal1.");</SCRIPT>";

should be

echo "<SCRIPT LANGUAGE='javascript'>addEmployee('".$id1."','".$fname1."',".$sal1.");</SCRIPT>";

And if you want to change it to OOP?

如果你想把它改成OOP?

<?php
    $employeeList[] = array('sdf3434', 'Bob', 123.34);
    $employeeList[] = array('wer335dg', 'Joe', 223);
?>
<html>
    <head>
        <script>
            function Employees() {
                this.list = new Array();
            }
            Employees.prototype.add = function (id, fname, sal) {
                this.list.push(new Array(id, fname, sal));
            };
            Employees.prototype.display = function () {
                for(var i=0, t = this.list.length;i<t;i++) {
                    var emp = this.list[i];
                    alert(emp[0]);
                    alert(emp[1]);
                    alert(emp[2]);
                }
            };
            var employees = new Employees();
            <?php
                foreach ($employeeList as $employee) {
                    list($id, $fname, $sal) = $employee;
                    printf("employees.add('%s', '%s', %f);\n", $id, $fname, $sal);
                }
           ?>
        </script>
    </head>
    <body>
        <a href="#" onclick="employees.display();">click</a>
    </body>
</html>

#4


The blog post Value Exchange from JavaScript/HTML page to PHP and from PHP page to JavaScript may be helpful for some.

从JavaScript / HTML页面到PHP以及从PHP页面到JavaScript的博客文章Value Exchange可能对某些人有所帮助。