无法从ajax响应中插入脚本字符串

时间:2013-07-30 04:14:05

标签: php html ajax response string

inserting script ajax response did not work

在php上,我有一个数组,其中有两部分如下

array('threeRowHtml'=> '<HTML output string>',
'jsCode'=> '<script output string>'
)

我为我的ajax调用返回该数组。我解析了响应,我可以接受其中两个字符串。我想将它们插入到我的页面和eval中以执行return js脚本。我可以插入“threeRowsHtml”,但是'jsCode'不起作用。

$.ajax({
            url: postUrl,
            type: "post",
            beforeSend:function(){
                process.show(); // just my popup
            },
            success: function(data){
                data = $.parseJSON(data);

                if(data.returnCode == 1){
                    //var jsCode = eval("(" + data.jsCode + ')');
                    console.log(data.jsCode); // print out OK
                    $('#rp_script').replaceWith(data.jsCode); // did not work
                    $('#rp_content').replaceWith(data.threeRowsHtml); // insert into page OK

                }
                else{
                    $('#rp_errors').replaceWith(data.errorHtml);
                }

                process.hide();
            }
        }) 

以下是插入回复的位置

<div id="rp_content">

</div>

<div id="rp_actions">

</div>

<div id="rp_script">

</div>
<div id="rp_errors"></div>

返回脚本字符串的语法很好,因为如果它错了,它会注意到我的JS错误令牌。 结果总是为“jsCode”空字符串,我不知道它有什么问题。任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:1)

处理AFAIK,js代码然后从XHR响应中剥离,您可以通过在开始脚本标记的正下方添加debugger;行来测试是否正在解释您的JS代码。打开你的代码检查器/开发工具/看看它是否在你的显式断点处停止。

请参阅此内容以供参考。它可能与jQuery - script tags in the HTML are parsed out by jQuery and not executed

有关

答案 1 :(得分:0)

不喜欢响应被正确转义。字符串中没有未转义的内容。

答案 2 :(得分:0)

我发现了问题。 jquery html() strips out script tags

现在我可以将脚本打印到我的页面

$('#rp_script')[0].innerHTML = data.jsCode;

原因是,我仍然使用global.eval来执行我的脚本。