gpt4 book ai didi

javascript - 无法传递 json 数组

转载 作者:行者123 更新时间:2023-11-28 08:23:14 25 4
gpt4 key购买 nike

我的网页有一个“onload”处理程序,它调用一个 javascript 函数“handleLoad()”,在我尝试在 PHP 中传递 json_encode 的输出后,该函数现已停止工作(未被调用)。

 <body onload="handleLoad('<?php echo $myJsonArr ?>')">

我也尝试过:

 <body onload="handleLoad(<?php echo $myJsonArr ?>)">

和:

 <body onload='handleLoad("<?php echo $myJsonArr ?>")'>

玩弄引号,但什么也没有。 handleLoad() 不再被调用。

传递myJsonArr现在会阻止handleLoad()函数执行——我知道这一点是因为handleLoad()中的第一行代码(顺便说一下,它是javascript)看起来像这样:

 function handleLoad(jsonArr)
{
alert("just entered handleLoad()");

.....other code not shown, and 100% commented out during fixing this bug
}

上面的“警报”框将显示正常 - 直到我添加“jsonArr”JSON 嵌套数组,之后“警报”框根本不显示。我从handleLoad()中删除了除alert()框之外的所有代码,以消除任何其他原因——并且不会调用handleLoad(),尽管handleLoad()中现在唯一的事情是对alert()的简单调用。

jsonArr 是这样创建的,从数据库读取:

 $result = mysql_query($query);
$numrows = mysql_num_rows($result);
$theOuterArray = array();

for($i = 0; $i < $numrows; $i++)
{
$theRow = mysql_fetch_row($result);
$cityName = $theRow[1];
$lat = $theRow[2];
$lng = $theRow[3];
// AND SO ON FOR address, titleOnly, recordNum, cityName, etc. used next....

$nestedArray = array($cityName, $lat, $lng, $i, $address, $titleOnly,
$recordNum, $cityName, $stateName, $price);
$theOuterArray[] = $nestedArray;
}
$myJsonArr = json_encode($theOuterArray);
var_dump($myJsonArr);

这是 var_dump 向我展示的内容 - 为了简单起见,我只在数据库中放入一条记录:

 string(136) "[["Auburn","32.6121","-85.4819",0,"Main Street","Test to debug why handleLoad() not being invoked","53378577","Auburn","Alabama","995"]]" 

我在这里缺少什么吗?我成功读取了数据库,但是创建 json 数组并将其传递给我的“onload”处理程序会破坏代码。

编辑:建议在 Firefox 中的我的页面上提供在 body 标记中生成的 onload 的源代码,这里是:

  <body onload="handleLoad('[["Auburn","32.6121","-85.4819",0,"Main Street","Test to debug why handleLoad() not being invoked","53378577","Auburn","Alabama","995"]]')">

最佳答案

编辑:删除了之前的 jQuery 答案。

这有效。在传回 json 数组之前,您需要使用 htmlentities() 。

php:

<?php

$myVar = '[["Auburn","32.6121","-85.4819",0,"Main Street","Test to debug why handleLoad() not being invoked","53378577","Auburn","Alabama","995"]]';

$myVar = htmlentities($myVar);

?>

HTML:

<body onload="handleLoad('<?php echo $myVar; ?>')">

<script>
function handleLoad(data) {
alert(data);
}
</script>

</body>

关于javascript - 无法传递 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22739975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com