从AJAX动态加载JavaScript - 失败了吗?

时间:2011-11-13 23:53:24

标签: php javascript html ajax

我遇到了从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;
 }

这很好用!

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

有人知道如何修复它吗?

问候!

1 个答案:

答案 0 :(得分:0)

我想你必须逃避你的撇号:

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

你看:onclick="Clicked()"

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

一起使用

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

试着逃避你的撇号:)

此致