【问题标题】:Make a submit button POST and AJAX call same time?同时进行提交按钮 POST 和 AJAX 调用?
【发布时间】:2015-01-25 08:38:39
【问题描述】:

我有这个表单,可以 POST 到 show_aht2.php,但我也希望它进行 AJAX 调用,您在下面的代码中可以看到。那么,我怎样才能做到这两点,这样用户就不会去另一个呢?我希望用户留在 map.php

提前致谢

map.php

    <form action="show_aht2.php" method="post">
           <input type="radio" name="date_selected" value="1d" checked="checked"/>1d
           <input type="radio" name="date_selected" value="1w" />1w
           <input type="radio" name="date_selected" value="1m" />1m
           <input type="radio" name="date_selected" value="3m" />3m
           <input type="submit" id="aht_btn" name="get_aht" value="Get AHT" />
    </form>


<script type="text/javascript">
        $(document).ready(function() {
                $('#aht_btn').click(function(){
                    $.ajax({
                    type:"GET",
                    url : "show_aht2.php",
                    data:{ } , // do I need to pass data if im GET ting?
                    dataType: 'json',
                    success : function(data){
                       //doing stuff
                        //get the MIN value from the array
                            var min = data.reduce(function(prev, curr) {
                                return isNaN(+curr['aht_value']) || prev < +curr['aht_value'] ? prev : +curr['aht_value'];
                            }, 1000000);

                        //  alert("min:" + min); //return min for debug

                            //get the MAX value from the array
                            var max = data.reduce(function(prev, curr) {
                              return isNaN(+curr['aht_value']) || prev > +curr['aht_value'] ? prev : +curr['aht_value'];
                            }, -1000000); 

                            //alert("max:" + max); //return max number for debug

                            //function for calculation of background color depending on aht_value               
                            function conv(x){
                                return Math.floor((x - min) / (max - min) * 255);
                            }

                            //function for background color
                            //if NA then show white background, either show from green to red
                            function colorMe(v){
                              return v == 'NA' ? "#FFF" : "rgb(" + conv(v) + "," + (255-conv(v)) + ",0)";
                            }

                        //going through all DIVs only once with this loop
                        for(var i = 0; i < data.length; i++) { // loop over results
                        var divForResult = $('#desk_' + data[i]['station']); // look for div for this object
                        if(divForResult.length) { // if a div was found
                            divForResult.html(data[i]['aht_value']).css("background-color", colorMe(data[i]['aht_value']));
                        //  alert("station " + data[i]['station'] + " <br>aht value" + data[i]['aht_value'] + "<br>timestamp:"+data[i]['ts_generated']);
                        }//end if
                        }//end for  
                    }//end success
                });//end ajax   
              });//end click
            });//end rdy
        </script>

show_aht2.php

    if (isset($_POST['get_aht'])) {
    if($_POST['date_selected'] == "1d" )//yesterdays result  and using past 10 minute
    {
        $start_date = $one_day;
        //$interval_value = "10 MINUTE";
        //echo $start_date;
    }
    elseif($_POST['date_selected'] == "1w" )//1 week results
    {
        $start_date = $one_week;
        //$interval_value =  "7 DAY";
        //echo $start_date;
    }
    elseif($_POST['date_selected'] == "1m" )//1 month results
    {
        $start_date = $one_month;
        //$interval_value =  "30 DAY";
        //echo $start_date;
    }
    elseif($_POST['date_selected'] == "3m" )//3 month results
    {
        $start_date = $three_month;
        //$interval_value =  "90 DAY";
        //echo $start_date;
    }
}


/* what I expect from ther call back*/
$result = array();
    foreach ($memo as $username => $memodata) {
    if (in_array($username, array_keys($user))) {
    // Match username against the keys of $user (the usernames) 
    $userdata = $user[$username];
    //if AHT is null give N/A as value
    if (is_null($memodata['aht_value'])) {
        $result[] = array( 'username'  => $userdata['username'],
                                             'aht_value' => 'NA',
                                             'station'  => $userdata['station']//,
                                            // "ts_generated" =>  $userdata['ts_generated'] 
                                            );
    }//end inner if 
    //else give the actual value of AHT without the decimals
    else {
        $result[] = array( 'username'  => $userdata['username'],
                                             'aht_value' => substr($memodata['aht_value'],0,-3),
                                             'station'   => $userdata['station']//,
                                        //   "ts_generated" =>  $userdata['ts_generated']   
                                        );
    }//end else
    }//end outer if
    }//end for

echo json_encode($result);

【问题讨论】:

  • 制作按钮type="button",这样它就不会提交表单。
  • @DavidNguyen 我的 show_aht2.php 脚本正在查询多个表并在 map.php 上从中返回值
  • 您不能同时进行正常提交和 Ajax。选择一个或另一个。您也不能同时进行 POST 和 GET 操作。任选其一。
  • @developerwjk 好吧,不是同时。但他可以做一个带有回调的 POST,然后提交表单。
  • @northkildonan,是的,但完全不清楚他要做什么,因为 ajax 调用的 success 方法中没有任何内容。我们有一个什么都得不到的 GET,但据说期望 Json 来自一个只处理 POST 的 PHP 页面。这里的目标一清二楚。

标签: javascript php jquery html ajax


【解决方案1】:

试试:

<script type="text/javascript">
    $(document).ready(function() {
            $('#aht_btn').click(function(event){
                event.preventDefault();
                $.ajax({
                type:"GET",
                url : "show_aht2.php",
                data:{ } , // do I need to pass data if im GET ting?
                dataType: 'json',
                success : function(data){
                   //doing stuff
                }//end success
            });//end ajax   
          });//end click
        });//end rdy
    </script>

使用方法 preventDefault : http://api.jquery.com/event.preventdefault/

【讨论】:

    【解决方案2】:

    先调用 ajax,然后用 .submit() 提交表单,然后回调 ajax。

    <form action="show_aht2.php" method="post" id="formtopost">
    
    <script type="text/javascript">
        $(document).ready(function() {
            $('#aht_btn').click(function() {
                $.ajax({
                    type: "GET",
                    url: "show_aht2.php",
                    data: {}, // do I need to pass data if im GET ting?
                    dataType: 'json',
                    success: function(data) {
                        //doing stuff
                        //end success
                    },
                    always: function() {
                        //submit form !!!
                        $("#formtopost").submit();
                    }
                }); //end ajax   
            }); //end click
        }); //end rdy
    </script>
    

    【讨论】:

    • 我的按钮 FORM 该怎么做?我是留下它输入“提交”还是将其作为“按钮”?
    • 如果你让它“提交”,你必须使用“event.preventDefault();”通过将其用作按钮,您必须使用脚本提交表单...我也将 id 添加到表单标签。
    • 所以您在“成功”中添加的代码行必须放在所有函数之前,因为我需要先发布表单,然后才能获得回调
    • 你不能先发帖,你必须先调用ajax然后提交表单。在 .always() 构造中有这样的东西很好
    • 它在控制台中给我一个错误.. 预期的标识符 在 function() 之后?
    【解决方案3】:

    您可以使用 ajax 提交表单,而不是同时尝试两者

    可能是这样的吗?

    <script type="text/javascript">
        $(document).ready(function() {
            $('#aht_btn').click(function(){
    
                // This prevents the form from submitting
                event.preventDefault();
    
                // Capture form input
                var $form = $(this);
                var serializedData = $form.serialize();
    
                // Run the ajax post
                $.ajax({
                    url : "show_aht2.php",
                    type:"POST",
                    data: serializedData
                    success: function(response) {
                        // Do something
                    }
                });
    
              });//end click
            });//end rdy
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 2020-01-20
      相关资源
      最近更新 更多