简体   繁体   English

如何在不重新加载页面的情况下提交数据?

[英]How to submit data without reloading page?

I have been trying to solve this problem for a long long time.我一直在尝试解决这个问题很长时间。 I'm new to web developing.我是 web 开发的新手。 What I'm trying to do is that when I'm click to submit button for submitting the values, the page should remains to it's position, but instead it's automatically goes to top, which I don't want that.我想要做的是,当我单击提交按钮以提交值时,页面应该保留在它的 position 上,但它会自动转到顶部,这是我不想要的。

<!DOCTYPE html>
<html >
<head>
   <style>
   .bigbox{
    height: 600px;
    width: 500px;
    background: olive;
    margin: 10px;
}
   </style>
</head>
<body>
<div class="bigbox">1</div>
<div class="bigbox">2</div>
<h4>type the range of numbers:</h4>
    <form id="myform">
            <input type="text" name="num1" placeholder="num1">
            <input type="text" name="num2" placeholder="num2">
            <button type="submit" name="submit" value="submit">Submit</button>
            <button type="reset">Reset</button>
    </form>
    <?php
        if(isset($_GET['submit']))
        {
            $num1=$_GET['num1']; 
            $num2=$_GET['num2'];
            $prefix=array("st","nd","rd","th");
         for($j = $num1 ; $j<=$num2;$j++)
         {
             switch($j)
             {
                 case ( $j%100==11 || $j%100==12 || $j%100==13 ); $i=3; break;
                 case $j%10==1: $i=0;break;
                 case $j%10==2; $i=1;break;
                 case $j%10==3; $i=2;break;
                 default : $i=3;
             }
             echo "this is the ".$j.$prefix[$i]." number "."<br>";
         } 
        } 
    ?>
</body>
</html>

I have created a pen with the closest approach to solve such problem, To achieve this using javascript Fetch API我已经用最接近的方法创建了一支笔来解决这个问题,为了实现这一点,使用 javascript Fetch API

 const formElement= document.getElementById("myform");
 formElement.addEventListener('submit',(e)=>{
   e.preventDefault();
   const formData = new FormData(formElement);
   fetch(`api/url`, {
     method: 'POST',
     body: formData,
   })
   .then(result  => result .json())
   .then(data=> console.log(data)) //after form submit
   .catch((err)=>console.log(err));
});

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values. FormData接口提供了一种方法来轻松构造一组表示表单字段及其值的键/值对。

For browser compatibility of fetch API check This link .对于 fetch API 的浏览器兼容性,请查看此链接

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

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