简体   繁体   English

调用ajax函数onload并单击按钮

[英]call ajax function onload and on button click

I want to show report base on the election date. 我想显示基于选举日期的报告。 when I call the function showReport() on form load is working, but it's not working when I call that function on button click. 当我在窗体加载中调用函数showReport()时可以正常工作,但是在单击按钮时调用该函数时却无法正常工作。

Report members 报告成员 图片

<script>
function showReport(){
   var from = $('#from').val();
   var to = $('#to').val();
   var str = $('#str').val();
 if(from == '' && to == '')
 {
    var from = '$from';
    var to = '$to';
 }
$.ajax({
    url: "crm_data_report.php?type="+str+"&from="+from+"&to="+to,
    method: "POST",
    success: function(data) {
    console.log(data);
    var date = [];
    var value = [];
    for(var i in data)
    {
    date.push(data[i].date);
    value.push(data[i].value);
    }
    var color = Chart.helpers.color;
    var chartdata = {
    labels: date,
    datasets :
    [
    {
    label: 'Members',
    backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
    borderColor: window.chartColors.red,
    borderWidth: 1,
    data: value
    }
    ]
    };
    var ctx = $("#mycanvas");
    var barGraph = new Chart(ctx, {
    type: 'bar',
    data: chartdata
    });
    },
    error: function(data) {
    console.log(data);
    }
    });
}

The code I called the function on load and on button click. 我在加载和单击按钮时调用了该函数的代码。

<script>
$(document).ready(function(){
   showReport();
});
$('#filter').click(function(){
    showReport();
});
</script>

Replace the code block with this: 用以下代码替换代码块:

$(function(){
    $('#filter').click(function(){
        showReport();
    });    
})

Its a very common issue you are binding the click event when the button is not available to dom yet , so you have to bind it when dom tree is ready. 这是一个非常普遍的问题,当按钮尚不适用于dom时,您要绑定click事件,因此必须在dom树准备好时绑定它。

This is on a hunch, there's nothing wrong with your code. 这是预感,您的代码没有错。 Could you please try 你能试一下吗

<script>
$(document).ready(function(){
   showReport();
   $('#filter').click(function(){
    showReport();
   });
});
</script>

It is possible that the DOM has not loaded completely (#filter element) when you are attaching the click handler to it. 将点击处理程序附加到DOM时,DOM可能未完全加载(#filter元素)。

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

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