我正在尝试使用PHP来定义一些JavaScript来定义变量。变量中有一个小jQuery,它应该由客户端呈现。我说“应该”但真的意味着我想要它。我应该怎么做才能使o2与o1相同(即隐藏jQuery)?
谢谢!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title></title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script>
$(function() {
var o1={"foo":{"bar": "abc/index.php?="+$("#id").val()}};
console.log(o1);
<?php
$d='abc/index.php';
$json='{"foo":{"bar": "'.$d.'?id=\"+$(\"#id\").val()"}}';
//echo($json);
$json=json_decode($json);
//echo(print_r($json,1));
$json=json_encode($json);
//echo($json);
echo("var o2=".$json.";");
?>
console.log(o2);
});
</script>
</head>
<body>
<input type="hidden" id="id" value="123" />
</body>
</html>
答案 0 :(得分:0)
未经测试,可能包含错误:
<script>
$(function() {
var o1={"foo":{"bar": "abc/index.php?="+$("#id").val()}};
console.log(o1);
<?php
$d='abc/index.php';
$json='{"foo":{"bar": "' . $d . '?="+$("#id").val()}}';
echo("var o2=".$json.';');
?>
console.log(o2);
});
</script>
答案 1 :(得分:0)
我更喜欢使用json_encode生成json,以避免解析和验证json时出现意外问题。
json_encode和json_decode仅适用于UTF-8,如果它有特殊字符,则另一个字符集将产生一个空字符串。
<script>
<?php
$d = "abc/index.php";
$json['foo']['bar'] = $d . '?id=$("#id").val()';
echo "var o2 = ".json_encode($json);
?>
console.log(o2);
</script>
答案 2 :(得分:0)
你有这个:
<input type="hidden" id="id" value="123" />
所以我可以假设你从数据库中获取了这个id吗?也许是这样的:
<input type="hidden" id="id" value="<?php echo $row[id];?>" />
如果是这种情况,请执行以下操作(我测试并运行):
您无需隐藏输入即可。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title></title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script>
$(function() {
<?php
//From your SQL query you obtained
//$row['id'] = 123;
$id = $row['id'];
?>
var o1={"foo":{"bar": "abc/index.php?=" + <?php echo $id ?>}};
console.log(o1);
<?php
$d='abc/index.php';
$json='{"foo":{"bar": "'.$d.'?='.$id.'"}}';
//echo($json);
$json=json_decode($json);
//echo(print_r($json,1));
$json=json_encode($json);
//echo($json);
echo("var o2=".$json.';');
?>
console.log(o2);
});
</script>
</head>
<body>
</body>
</html>