将PHP数组传递给js时出错

时间:2015-11-10 15:20:46

标签: javascript php

我在PHP中有这个数组($test

array (size=4)
  1 => string 'test1@mail.example' (length=17)
  2 => string 'test2@mail.example' (length=17)
  3 => string 'test3@mail.example' (length=17)
  4 => string 'test4@mail.example' (length=17)

并希望将其传递给javascript。我的目标是在AJAX查询中使用它。

所以我做了以下

var test = "<?php echo json_encode($test); ?>";
$.post("../path/to/file.php",
{
  test: test,
},
function(data,status)
{ 
  ...
});

但以下是每次触发

SyntaxError: missing ; before statement
var test = "{"1":"test1@mail.example","2":"test1@mail.

1 个答案:

答案 0 :(得分:3)

不要将json输出括在引号中。这是不必要的:

var test = <?php echo json_encode($test); ?>;

json_encode()已经添加了任何必要的"个字符,而您的额外"会破坏语法,例如

PHP:

$foo = 'ab"c';

json_encode($foo) -> "ab\"c";

JS:

var test1 =  <?php echo json_encode($foo); ?>;
var test2 = "<?php echo json_encode($foo); ?>";

出现为:

var test1 = "ab\"c";      // this line is ok
var test2 = ""ab\"c"";  // this line is fubar
            ^--start string
             ^--end string
              ^^---undeclared/undefined variable