简体   繁体   English

JS:提交时调用函数

[英]JS: Calling function on Submit

Hello everyone I'm still new to JS, so I want to ask about calling a function when form is submitted. 大家好,我还是JS新手,所以我想问一下在提交表单时调用函数的问题。

[update] Form [更新]表格

<div id="dashboard-side">

    <form id="report" class="form-horizontal" method="post" action="<?= site_url('api/load_report') ?>"> <!-- onsubmit="location.reload()" -->            
        <fieldset>
            <div class="control-group center_div">                    
                <label class="control-label">Sales Name</label>                    
                <div class="controls">
                    <input type="text" name="sales_name" class="form-control input-xlarge txt-up" value="<?php echo set_value('cust_name'); ?>" placeholder="Enter Customer Name" style="height: 30px;"/>                       
                </div>
            </div>

            <div class="control-group center_div">
                <div class="controls form-inline">
                    <input id="get_report" type="submit" class="btn btn-success btn-inline " value="Get Report" style="width:110px; margin-left: -155px;"/>
                </div>  
            </div>                
            <table border="1" width="100%" style="background-color: #dfe8f6;">
                <tr>
                    <td width="154px"><strong>Customer Name</strong></td><td width="128px"><strong>Activity</strong></td>
                    <td width="244px"><strong>Detail</strong></td><td width="141px"><strong>Start Time</strong></td>
                    <td width="142px"><strong>Finish Time</strong></td><td width="39px" style="text-align:center"><strong>Note</strong></td>
                    <td style="margin-left: 50px"><strong>Action</strong></td>   
                </tr>
            </table>
            <!------------------------------------------------------------------------------------->               
            <div id="xreport" class="table-hover" style="background-color: #EAF2F5"></div>


        </fieldset>
    </form>
    </div>

Controller 控制者

public function load_report() { 公共功能load_report(){

    $this->db->where('user_id', $this->input->post('sales_name'));

    $query = $this->db->get('activity');
    $result = $query->result_array();
    $this->output->set_output(json_encode($result));  }

JS JS

var load_report = function() {
    $.get('api/load_report', function(o){

        var output = '';            
        for (var i = 0; i < o.length; i++){
            output += Template.dodo(o[i]);

        }            
        $("#xreport").html(output);
    }, 'json');
};

If I call the function on form load it works fine, but I want to call it on form submit, how to do that? 如果我在表单加载时调用该函数,则可以正常工作,但是我想在表单提交时调用该函数,该怎么做?

Here is what I tried 这是我尝试过的

var load_report = function () {
    $("#report").submit(function(){
     $.get('api/load_report', function(o){            
        var output = '';            
        for (var i = 0; i < o.length; i++){
            output += Template.dodo(o[i]);

        }            
        $("#xreport").html(output);
    }, 'json');
});
};

Instead of assigning the array into my #div, it shows the array data in the new blank tab like this: my current result so far 它没有将数组分配给我的#div,而是在新的空白标签中显示了数组数据,如下所示: 到目前为止,我的当前结果

any help would be appreciated, thanks. 任何帮助,将不胜感激,谢谢。

Update: New calling function 更新:新的调用函数

  var load_report = function () {
    $("#report").submit(function (evt) {
        evt.preventDefault();
        var url = $(this).attr('action');
        var postData = $(this).serialize();

        $.post(url, postData, function (o) {
            if (o.result == 1) {
                var output = '';
                Result.success('Clocked-in');
                for (var i = 0; i < o.length; i++) {
                    output += Template.dodo(o[i]); //this data[0] taken from array in api/load_report
                    console.log(output);
                    $("#xreport").html(output);
                }
            } else {
                Result.error(o.error);
                console.log(o.error);
            }
        }, 'json');
    });
};

with this new calling function I'm able to retrieve data from api/load_report without getting stuck on e.preventDefault or even open a new tab, I console.log and the result show correctly in the console, but it doesn't show on the div somehow. 有了这个新的调用函数,我可以从api/load_report检索数据而不会卡在e.preventDefault上,甚至不用打开一个新标签页,我console.log并且结果在控制台中正确显示,但是在控制台上却不显示div不知何故。

my template.js (if needed) 我的template.js(如果需要)

this.dodo = function(obj){
    var output ='';                     
    output +='<table border=1, width=100%, style="margin-left: 0%"';
    output += '<tr>';
    output += '<td width=120px>' + obj.user_id + '</td>';
    output += '<td width=120px>' + obj.cust_name + '</td>';
    output += '<td width=100px>' + obj.act_type + '</td>';
    output += '<td width=190px>' + obj.act_detail + '</td>';
    output += '<td width=110px>' + obj.date_added + '</td>';
    output += '<td width=110px>' + obj.date_modified + '</td>';         
    output += '<td style="text-align:center" width=30px>' + obj.act_notes + '</td>';
    output += '</tr>';        
    output +='</table>';        
    output += '</div>';        
    return output;
};

Result (note, user_id = form.sales_name) result preview 结果(注意,user_id = form.sales_name) 结果预览

You could alway do the following: 您可以始终执行以下操作:

 function myFunction() { alert("Hello! I am an alert box! in a function"); } 
 <form> <input type="text" /> <input type="submit" value="submit" onclick="return myFunction();"/> </form> 

PS This question might be answered in this question already, add onclick function to a submit button PS此问题可能已经回答了这个问题, 将onclick函数添加到提交按钮

Try to prevent form to get submit by using preventDefault() 尝试通过使用preventDefault()阻止form获取submit

$("#report").submit(function(e){ //add param "e"
     e.preventDefault(); //to prevent form to submit
     //further code....
});

Ok just try 好吧,尝试

function mysubmit(){
     $.get('api/load_report', function(o){            
        var output = '';            
        for (var i = 0; i < o.length; i++){
            output += Template.dodo(o[i]);

        }            
        $("#xreport").html(output);
    }, 'json');
}

as your script and 作为您的脚本和

<form id="report" class="form-horizontal" onsubmit="event.preventDefault(); mysubmit();" method="post" action="<?= site_url('api/load_report') ?>">

as your form 作为你的形式

First off, I would advise against using onclick or onsubmit directly on the dom like so. 首先,我建议不要像这样直接在dom上使用onclickonsubmit

<form onsubmit="myFunction();"></form>

The biggest reason for me is that it negatively impacts readability and sometimes even future maintenance of the project . 对我来说,最大的原因是它对可读性产生了负面影响,有时甚至会影响项目的未来维护。 It is nice to keep html and javascript separate unless you are using a framework that provides templating features/functionality such as angularjs. 最好将html和javascript分开,除非您使用的框架提供模板功能/功能,例如angularjs。

Another big one is that you can only have one in-line event present and it is easy to accidentally overwrite, which can lead to confusing bugs. 另一个大问题是,您只能存在一个内联事件,并且很容易意外覆盖,这可能导致令人困惑的错误。

The reason it is going to a new tab is because of the .submit() . 之所以要进入新标签页是因为.submit() This will call your function, but then proceed with internal jQuery event handling which includes refreshing the page. 这将调用您的函数,但随后进行内部jQuery事件处理,其中包括刷新页面。 There are two solutions I see most viable here. 我在这里看到两种最可行的解决方案。

1st Solution: 第一种解决方案:

Add a event.preventDefault(); 添加一个event.preventDefault(); at the start of your function to stop jQuery from refreshing your page. 在函数开始时,阻止jQuery刷新页面。

$("#report").submit(function(e) {
      e.preventDefault();
 });

2nd Solution (Likely better): 第二个解决方案(可能更好):

You are making an ajax call with $.get(...) . 您正在使用$.get(...)进行ajax调用。 You could add an event listener on a button (probably on the button used to submit the form) that fires your ajax call. 您可以在触发您的ajax调用的按钮(可能在用于提交表单的按钮上)上添加事件侦听器。 Here is an example that assumes the submit button has the id of loadData . 这是一个示例,假定loadData按钮的ID为loadData

$("#loadData").click(function(){
   $.get('api/load_report', function(o){            
      var output = '';            
      for (var i = 0; i < o.length; i++){
          output += Template.dodo(o[i]);
      }            
      $("#xreport").html(output);
  }, 'json');
}

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

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