如何执行JavaScript字符串变量中的脚本?

时间:2014-02-12 15:16:31

标签: javascript jquery asp.net ajax

我有像

这样的javascript变量
 var str = "<!-- START Script Block for Chart Expense -->
   <div id='ExpenseDiv' align='center'>
    Chart.
   </div>
  <script type="text/javascript">
     var chart_Expense = new FusionCharts("../FusionCharts/FCF_Doughnut2D.swf", "Expense", "500", "350", "0", "0");
     chart_Expense.setDataXML("<graph caption='Expense' numberPrefix='' formatNumberScale='0' decimalPrecision='0'><set name='February' value='15.2' /><set name='April' value='716468.68' /><set name='May' value='541645.18' /><set name='June' value='681415.5' /><set name='July' value='575417.99' /><set name='August' value='436200.21' /><set name='September' value='159725' /><set name='November' value='0.53' /><set name='December' value='54.7' /></graph>");
     chart_Expense.render("ExpenseDiv");
      </script>
      <!-- END Script Block for Chart Expense -->"

我想在javascript端执行此脚本,该脚本位于javascript字符串变量中,并将其结果附加到页面中的一个控件中。 这意味着这个字符串的脚本块有funvtion“chart_Expense.setDataXML”和“chart_Expense.render”,我想在客户端执行此功能。

我现有的代码如下

javascript方

 function RebindChart() {
        var ddlChartType2Value = document.getElementById("ctl00_ContentPlaceHolder1_ddlChartType2").value;
        $.ajax({
            type: "POST",
            url: "DashBoardAccount.aspx/GetChatInfo",
            contentType: 'application/json; charset=utf-8',
            data: "{ charttype: '" + ddlChartType2Value + "' }",
            dataType: 'json',
            cache: false,
            success: function (result) {
                document.getElementById('ctl00_ContentPlaceHolder1_FCLiteral2').innerHTML = result.d;
            }
        });
    }

服务器端

 [System.Web.Services.WebMethod]
    public static string GetChatInfo(string charttype)
    {
        return BindExpense(charttype); // this function return string which is describe in above
    }

2 个答案:

答案 0 :(得分:0)

您可以尝试使用eval()查看http://www.w3schools.com/jsref/jsref_eval.asp 但是JSLINT会告诉你不要使用它; - )

答案 1 :(得分:0)

您可以尝试使用jQuery .html()将其附加到DOM。它将评估并执行返回字符串中包含的所有内容。

这有效:

$('#ctl00_ContentPlaceHolder1_FCLiteral2').html(result.d);

这不是:

document.getElementById('ctl00_ContentPlaceHolder1_FCLiteral2').innerHTML = result.d;

如图所示here

$(function () {

    // jQuery
    var resultJQ = "<script>alert('jQuery'); $('body').append('jQuery');<\/script>";
    $('body').append($('<div>').attr('id', 'scriptjq'));
    $('#scriptjq').html(resultJQ);

    // Javascript
    var resultJS = "<script>alert('Javascript'); $('body').append('Javascript');<\/script>";
    $('body').append($('<div>').attr('id', 'scriptjs'));
    document.getElementById('scriptjs').innerHTML = resultJS;

});

希望它有所帮助!