使用 AJAX 在页面加载时自动提交表单并获得 html 类型结果


auto submit form on pageload using AJAX and get html type result?

我正在尝试使用 ajax 在页面加载时自动提交表单,然后将 HTML(一堆将在 AJAX URL 上回显的div)返回我的 AJAX 页面。

首先,我的代码会自动提交表单,但它会忽略 AJAX 调用,因此用户将被带到表单的操作页面。

此外,如果我从我的 AJAX 代码中删除自动提交代码并通过提交按钮手动提交表单,我不会从 AJAX URL 页面获得任何回报!

这是我的整个代码:

window.onload = function(){
document.forms['myformR'].submit()  

  // this is the id of the form
    $("#myformR").submit(function() {
        var url = "results.php"; // the script where you handle the form input.
        $.ajax({
               type: "POST",
               url: url,
                dataType: "html", //expect html to be returned                
                success: function (response) {
                    $("#prores").html(response);

                }
             });
        return false; // avoid to execute the actual submit of the form.
    });
}

任何建议将不胜感激。

编辑,这是我的 ajax PHP URL 页面:

<?php
session_start();
?>
<?php
include "config/connect.php";
$searchList = "";
$clause = " WHERE ";//Initial clause
$sql="SELECT *
FROM `yt`
INNER JOIN `ATTRIBUTES` ON yt.subcats=ATTRIBUTES.type";//Query stub
if(isset($_POST['submit'])){
    if(isset($_POST['keyword'])){
        foreach($_POST['keyword'] as $c){
            if(!empty($c)){
                ##NOPE##$sql .= $clause."`".$c."` LIKE '%{$c}%'";
                $sql .= $clause . " (ATTRIBUTES.sizes LIKE BINARY '$c' OR ATTRIBUTES.colors LIKE BINARY '$c' OR ATTRIBUTES.type LIKE BINARY '$c')";
                $clause = " OR ";//Change  to OR after 1st WHERE
            }
        }
        $sql .= " GROUP BY yt.id ";
        //print "SQL Query: $sql<br />"; //<-- Debug SQl syntax.
        // Run query outside of foreach loop so it only runs one time.
        $query = mysqli_query($db_conx, $sql);
        //var_dump($query); //<-- Debug query results.
        // Check that the query ran fine.
        if (!$query) {
            print "ERROR: " . mysqli_error($db_conx);
        } else {
            // Use $query inside this section to make sure $query exists.
            $productCount = mysqli_num_rows($query);
            $i=0; // count the output amount
            if ($productCount > 0) {
                while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
        $sizesOption ="";
        $colorOption ="";
             $id = $row["id"];
             $product_name = $row["product_name"];
             $details = $row["details"];
             $details = preg_replace("/''''r''''n/", "", $details);
             $price = $row["price"];
             $category = $row["category"];
             $manu = $row["manu"];
             $sizez = $row["sizez"];
             $colours = $row["colours"];
             $colours = preg_replace('/'.$/', '', $colours);
             $sizez = preg_replace('/'.$/', '', $sizez); //Remove dot at end if exists
             $array = explode(',', $sizez);
             $arrayC = explode(',', $colours); //split string into array seperated by ','
             foreach($array as $value) //loop over values
             {
                 //echo $value . PHP_EOL; //print value
                 $sizesOption .='<option>'.$value.'</option>';
              }
            foreach($arrayC as $valueC) //loop over values
             {
                 //echo $value . PHP_EOL; //print value
                 $colorOption .='<option>'.$valueC.'</option>';
              }
                   $searchList .= '<div align="center" class="mypro" style="position:relative; width:270px; height:470px; border:solid 1px #CCC; margin:10px; float:left; overflow:hidden; padding:5px;">
<a class="overlay" href="product.php?id='.$id.'"></a>
<!--<a class="overlayBtns" href="">Quick View</a>-->
<div class="overlayAdd">

            <a style="font: bold 11px Arial;
  text-decoration: none; background-color: #FFF; color: #333333; padding: 10px; border:none; border-radius:4px; width:120px; height:30px;" id="go" rel="leanModal" name="test" href=".test'.$id.'">Qick View <i style="color:#000; font-size:18px;" class="fa fa-eye"></i></a>

           <div  style="display:none; display:none; width:580px; height:auto; background-color:#FFF; border-radius:4px; padding:12px;" class="test'.$id.'">

           <h2>'.$product_name.'</h2>
         <p style="text-align:left;">'.$details.'</p>
         <form id="form'.$id.'" class="form1" name="form1" method="post" action="cart.php">
         <p>
         <p style="text-align:left; font-weight:bold;">Size</p>
         <select id="sizeSelect"  name="sizeSelect" style="">
         '.$sizesOption.'
         </select>

         <p style="text-align:left; font-weight:bold;">Colour</p>
         <select id="colorSelect" name="colorSelect" style="">
         '.$colorOption.'
         </select>
         </p>
        <p style="text-align:left; font-weight:bold; width:100px; float:left;">Quantity</p> 
             <input min="1" type="number" id="quantity" name="quantity" value="1" />
        </p> 
        <p>
        <input type="hidden" name="pid" id="pid" value="'.$id.'" />
        <input type="hidden" name="moneyPrice" id="moneyPrice" class="moneyPrice" value="" />
        <input type="hidden" name="moneyCurreny" id="moneyCurreny" class="moneyCurreny" value="" />
        <input style="background-color:#000; color:#FFF;" type="submit"  value="ADD TO BASKET" />
      </form></p>
      <br><br>
      <a href="product.php?id='.$id.'">View Item Full Details</a><br><br>
<div class="share-buttons" data-url="http://enzua.com/product.php?id='.$id.'" data-text="http://enzua.com/product.php?id='.$id.'"></div>
        </div></div>

<img width="100%" src="product_images/'.$id.'Image1.jpg" alt=""  />

<p style="padding:2px;">'.$product_name.'</p>
<p style="padding:2px;">'.$manu.'</p>
    <div style="padding:5px;" class="price">
      <div class="prod-price"><span class=money>£'.$price.'.00</span></div>
    </div>
</div>';
                }
            }
        }
    }
}
?>
<?php 
echo $searchList;
exit(); 
?>

这是我的HTML表单:

    <form class="myformR" id="myformR" name="myformR" method="post" action="results.php">
    <input type="hidden" name="keyword[]" value="dress" />
    <input id="smt" type="submit" value="submit" name="submit" />
    </form>
<div id="prores"></div>

使用以下代码

 $(window).load(function(){
 // this is the id of the form
    var url = "results.php"; // the script where you handle the form input.
    $.ajax({
           type: "POST",
           url: url,
           data:$( "#myformR" ).serialize(),
           dataType: "html", //expect html to be returned                
           success: function (response) {
                $("#prores").html(response);
            }
         });
});
如果我

正确理解您的问题,您只想在页面加载时提交表单,并且当前使用您的代码它不是通过 ajax 提交的。你能试试下面的代码吗

$("#myformR").submit(function(e) {
  e.preventDefault();
  // your code
}

我想你需要的是这个

  $("#myformR").submit(function() {
        var url = "results.php"; // the script where you handle the form input.
        $.ajax({
               type: "POST",
               url: url,
          data: new FormData( this ),
      processData: false,
      contentType: false,
                dataType: "html", //expect html to be returned                
                success: function (response) {
                    $("#prores").html(response);
                }
             });
        return false; // avoid to execute the actual submit of the form.
    });

将表单数据与表单有关的信息一起发送到后端希望这有帮助