繁体   English   中英

使用按钮执行后如何加载JQuery函数?

[英]How to load a JQuery function after execute with button?

我是JQuery的新手,并且卡在了atm上。 我有一个MVC应用程序,可从Google API绘制图表。 我正在使用一个允许用户从DropDownList中选择项目的UI,单击“运行”,将加载图表。 我当前的问题是,当我进入视图时,图表将直接运行。 绘制图表的JQuery函数在GAStatisticsController中实现GetData ActionResult。

我有一个dropDownList,其中包含来自模型类的可选项目和一个按钮(“ GAStatisticsReport-Submit”)。 我只需要检查是否在DropDownList中选择了“ Visitors”项目,如果可以的话,我可以单击run,并且Charts会与访问者一起显示数据。 我该如何存档?

控制器具有一种称为CreateGAStatisticsReport的方法,该方法将数据返回到视图以供图表显示。 此方法具有一个ActionResult。 但是,当函数绘制图表时,它是从GetData ActionResult而不是GAStatistics绘制图表。

这是视图:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });
    google.load("visualization", "1", { packages: ["treemap"] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {
        $.get('/GAStatistics/GetData', {}, <--- here's GetData ActionResult in the Controller
            function (data) {
                var tdata = new google.visualization.DataTable();

                tdata.addColumn('date', 'Datum');
                tdata.addColumn('number', 'Besökare');

                for (var i = 0; i < data.length; i++) {
                    var dateStr = data[i].Date.substr(0, 4) + "-" + data[i].Date.substr(4, 2) + "-" + data[i].Date.substr(6, 2);
                    tdata.addRow([new Date(dateStr), parseInt(data[i].Visitors)]);
                }

                var options = {
                    title: "Number of unique visitors"
                };

                var chart1 = new google.visualization.AreaChart(document.getElementById('chart_div1'));
                var chart2 = new google.visualization.LineChart(document.getElementById('chart_div2'));
                var chart4 = new google.visualization.ColumnChart(document.getElementById('chart_div4'));

                chart1.draw(tdata, options);
                chart2.draw(tdata, options);
                chart4.draw(tdata, options);
            });
    }

</script>

<table class="adminContent">
         <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.StartDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.StartDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.EndDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.EndDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.GAStatisticsId ):
            </td>
            <td class="adminData">
                @Html.DropDownList("GAStatisticsId", Model.AvailableGAStatistics)
                <input type="button" id="GAStatisticsReport-Submit" class="t-button" value="@T("Run")" />
        </tr>
</table>

我的ViewModel(注意:选择SelectListItem“ Visitors”并且用户单击“ Run”按钮时,它应该执行并绘制图表):

    public class GAStatisticsListModel : BaseNopModel
    {
        public GAStatisticsListModel()
        {
            AvailableGAStatistics = new List<SelectListItem>();

            SelectListItem Visitors = new SelectListItem() { Text = "Besökare", Value = "1", Selected = false };
            SelectListItem PercentNewVisitors = new SelectListItem() { Text = "Nya Besökare (Procent)", Value = "2", Selected = false };
            SelectListItem ConversionRate = new SelectListItem() { Text = "Konverteringsgrad", Value = "3", Selected = false };



            AvailableGAStatistics.Add(Visitors);
            AvailableGAStatistics.Add(PercentNewVisitors);
            AvailableGAStatistics.Add(ConversionRate);
        }


        [NopResourceDisplayName("Admin.ShopStatistics.List.StartDate")]
        [UIHint("DateNullable")]
        public DateTime? StartDate { get; set; }

        [NopResourceDisplayName("Admin.ShopStatistics.List.EndDate")]
        [UIHint("DateNullable")]
        public DateTime? EndDate { get; set; }

         [NopResourceDisplayName("Admin.GAStatistics.GAStatistics.GAStatisticsList")]
        public int GAStatisticsId { get; set; }

        public List<SelectListItem> AvailableGAStatistics { get; set; }

    }
}

控制器(GetData将数据从CreateGAStatisticsReport传递到视图中的JQuery代码,以显示图表):

public class GAStatisticsController : Controller
    {

        //GET: /ShopStatistics/
        [HttpPost]
        public ActionResult GetData() 
        {
            return Json(CreateGAStatisticsReport(), JsonRequestBehavior.AllowGet);
        }



        public ActionResult GAStatistics()
        {
            return View(new GAStatisticsListModel());
        }


        private List<GAStatistics> CreateGAStatisticsReport()
        {

            var serviceAccountEmail = "xxxxxxxxx@developer.gserviceaccount.com";
            var certificate = new X509Certificate2(@"C:\Users\Desktop\NopCommerce\Presentation\Nop.Web\key.p12", "notasecret", X509KeyStorageFlags.Exportable);


            var credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = new[] { AnalyticsService.Scope.Analytics }
            }.FromCertificate(certificate));

            // Create the service.
            //Twistandtango
            var GoogleAnalyticsService = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "MyApp",
            });

            var request = GoogleAnalyticsService.Data.Ga.Get("ga:xxxxxxxx", "2014-01-24", "2014-01-30", "ga:visitors");
            //Specify some addition query parameters
            request.Dimensions = "ga:date";
            request.Sort = "-ga:date";
            request.MaxResults = 10000;

            //Execute and fetch the results of our query
            Google.Apis.Analytics.v3.Data.GaData d = request.Execute();


            List<GAStatistics> ListGaVisitors = new List<GAStatistics>();

            foreach (var row in d.Rows)
            {

                GAStatistics GaVisits = new GAStatistics(row[0], row[1]);
                ListGaVisitors.Add(GaVisits);

            }


            return ListGaVisitors;

        }
    }

对于您想要的内容,您不能使用google.setOnLoadCallback(drawChart)(请参阅此链接也了解其原因)。 如果我了解您要做什么,则必须在按钮上设置一个事件,该事件将执行drawChart()函数。

像这样:

$("#GAStatisticsReport-Submit").click(function(){ drawChart() })

因此,当您单击该按钮时,将绘制图表。 要仅在选择“访客”时绘制图表,您必须执行以下操作:

$("#GAStatisticsReport-Submit").click(function(){ 
    if($("select[name='GAStatisticsId'] option:selected").text()=="Visitors")
        drawChart() 
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM