SyntaxError:带有JSON数组的未终止字符串文字

时间:2017-08-05 20:52:02

标签: javascript json

所以我有......

 var newfavz = 'Array (


[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]
[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]
[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]

)
';

在我的console.log上,但不知何故有一个语法错误:未终止的字符串文字。我环顾四周,尝试使用str_replace“/”和“//”之类的方法或像.replace这样的正则表达式(/ ^ / + / g,'');因为似乎JavaScript不允许将字符串分成多行或类似的东西。

这一切都始于SQL查询,如此......

$favurl = [];
$favquery = "SELECT * FROM userfavs WHERE users = '$username'";
$favresult = mysqli_query($conn, $favquery);

while($row = mysqli_fetch_assoc($favresult)) {

array_push($favurl, $row['fav_id']);

之后,我做了

var newfavz = <?php print_r ($favurl); ?>

导致了上述情况。

我有什么方法可以用来解决语法错误吗?谢谢!

3 个答案:

答案 0 :(得分:0)

因为js中不允许使用多行字符串:

"A
 B"

语法错误。您可以删除所有换行符并用\ n替换它们,或者使用模板文字:

`A
 B`

在您的代码中:

var newfavz =` <?php print_r ($favurl); ?>`;

错误太多了。但是字符串仍然无法使用,需要对其进行解析。看看JSON或编写自己的小解析器。

答案 1 :(得分:0)

使用ES6 template literals

var newfavz = `Array (


[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]
[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]
[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]

)
`;

或者使用反斜杠:

var newfavz = 'Array (\n\
\n\
\n\
[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n\
[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n\
[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n\
\n\
)\
';

或连接:

var newfavz = 'Array (\n' +
  '\n' +
  '\n' +
  '[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n' +
  '[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n' +
  '[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\n' +
  '\n' +
  ')\n';

\n用于表示newline

答案 2 :(得分:0)

您必须在每行的末尾加上反斜杠才能生成多行字符串:

var newfavz = 'Array (\
[0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\
[1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\
[2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "]\
)\
';