gpt4 book ai didi

php - 从 AJAX 动态加载 JavaScript - 失败?

转载 作者:行者123 更新时间:2023-11-28 10:07:09 25 4
gpt4 key购买 nike

我在从 Ajax 动态加载 javascript 函数时遇到问题。我想用 Ajax 更新 HTML 的某些部分。假设我想放置一个按钮并将 JavaScript 函数动态附加到该按钮。例如:...

<head>

<script src="ajax.js" type="text/javascript"></script>

<script type="text/javascript">
function f_OnLoadMain()
{
fParseBrowserInfo();
getJSFromServer();
getHTMLFromServer();

}
</script>
</head>

<body onload="f_OnLoadMain()">
<div id="AjaxArea" width="100%" height="100%" align="left" valign="top" >
<!-- Updated with ajax -->
</div>
</body>
</html>

----- getJSFromServer() - 调用 php 代码:

<?php
$somesource = '
function Clicked(){
alert("Clicked");
}
';

class TestObject{
public $source = "";

function TestObject()
{
$this->source = "";
}

function setSource($source){
$this->source = $source;
}
}
$ti = new TestObject();
$ti->setSource($somesource);
echo(json_encode($ti));
?>

脚本插入:

var oHead = document.getElementsByTagName('HEAD').item(0);
if (oScript){
oHead.removeChild(oScript);
}
oScript = document.createElement("SCRIPT");
oScript.type = 'text/javascript';
oScript.text = oScript.source;
oHead.appendChild( oScript);

和 getHTMLFromServer() - 调用 php :

<?php
$error = 0;

$someText = '
<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()" value="SomeBtn">
';
class TestObject{
public $src = "";
public $error = 0;

function TestObject()
{
$this->error = 0;
$this->src = "";
}

function setSrcString($sample){
$this->src = $sample;
}
}
$ti = new TestObject();
$ti->error = $error;
$ti->setSrcString($someText);
echo(json_encode($ti));
?>
<小时/>

然后内容更新为:

 var dynamicArea = document.getElementById("AjaxArea");
if(dynamicArea != null)
{
dynamicArea.innerHTML = obj.src;
}

效果很好!

因此,当页面加载时,按钮显示正常,但按下按钮不会调用函数 Clicked()。

有人知道怎么解决吗?

问候!

最佳答案

我想你必须转义你的撇号:

<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()"    value="SomeBtn">

您会看到:onclick="Clicked()"

与:function Clicked(){alert("Clicked"); }

它呈现为:onclick="alert("clicked")"

尝试逃避你的撇号:)

问候

关于php - 从 AJAX 动态加载 JavaScript - 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8115797/

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