Javascript 无需重新加载页面即可提交表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2866063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:15:59  来源:igfitidea点击:

Submit form without page reloading

phpjavascripthtmlforms

提问by

I have a classifieds website, and on the page where ads are showed, I am creating a "Send a tip to a friend" form...

我有一个分类广告网站,在展示广告的页面上,我正在创建一个“向朋友发送提示”表单...

So anybody who wants can send a tip of the ad to some friends email-adress.

因此,任何想要的人都可以将广告提示发送给一些朋友的电子邮件地址。

I am guessing the form must be submitted to a php page right?

我猜表单必须提交到 php 页面对吗?

<form name='tip' method='post' action='tip.php'>
Tip somebody: <input name="tip_email" type="text" size="30" onfocus="tip_div(1);" onblur="tip_div(2);"/>
 <input type="submit" value="Skicka Tips"/>
 <input type="hidden" name="ad_id" />
 </form>

When submitting the form, the page gets reloaded... I don't want that...

提交表单时,页面会重新加载...我不希望那样...

Is there any way to make it not reload and still send the mail? Preferrably without ajax or jquery...

有没有办法让它不重新加载并仍然发送邮件?最好没有 ajax 或 jquery ......

Thanks

谢谢

采纳答案by jkilbride

You'll need to submit an ajax request to send the email without reloading the page. Take a look at http://api.jquery.com/jQuery.ajax/

您需要提交 ajax 请求以发送电子邮件而无需重新加载页面。看看http://api.jquery.com/jQuery.ajax/

Your code should be something along the lines of:

你的代码应该是这样的:

$('#submit').click(function() {
    $.ajax({
        url: 'send_email.php',
        type: 'POST',
        data: {
            email: '[email protected]',
            message: 'hello world!'
        },
        success: function(msg) {
            alert('Email Sent');
        }               
    });
});

The form will submit in the background to the send_email.phppage which will need to handle the request and send the email.

表单将在后台提交到send_email.php需要处理请求并发送电子邮件的页面。

回答by Juan Diego

I've found what I think is an easier way. If you put an Iframe in the page, you can redirect the exit of the action there and make it show up. You can do nothing, of course. In that case, you can set the iframe display to none.

我找到了我认为更简单的方法。如果您在页面中放置了一个 Iframe,您可以将操作的退出重定向到那里并使其显示出来。当然,你什么也做不了。在这种情况下,您可以将 iframe 显示设置为无。

<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
    <input type="submit" value="Skicka Tips">
    <input type="hidden" name="ad_id" value="2">            
</form>

回答by Sean Kinsey

You either use AJAX or you

你要么使用 AJAX 要么你

  • create and append an iframe to the document
  • set the iframes name to 'foo'
  • set the forms target to 'foo'
  • submit
  • have the forms action render javascript with 'parent.notify(...)' to give feedback
  • optionally you can remove the iframe
  • 创建 iframe 并将其附加到文档
  • 将 iframe 名称设置为 'foo'
  • 将表单目标设置为 'foo'
  • 提交
  • 让表单操作使用“parent.notify(...)”呈现 javascript 以提供反馈
  • 您可以选择删除 iframe

回答by Dragan Marjanovic

Fastest and easiest way is to use an iframe. Put a frame at the bottom of your page.

最快和最简单的方法是使用 iframe。在页面底部放置一个框架。

<iframe name="frame"></iframe>

<iframe name="frame"></iframe>

And in your form do this.

并以您的形式执行此操作。

<form target="frame">
</form>

and to make the frame invisible in your css.

并使框架在您的 css 中不可见。

iframe{
  display: none;
}

回答by Rhalp Darren Cabrera

Submitting Form Without Reloading The Page And Get Result Of Submitted Data In The Same Page

提交表单而不重新加载页面并在同一页面中获取提交数据的结果

Here's some of the code I found on the internet that solves this problem :

这是我在互联网上找到的一些解决此问题的代码:

1.) IFRAME

1.)框架

When the form submitted the action will be executed and target the specif iframe to reload.

当表单提交时,动作将被执行并针对特定的 iframe 重新加载。

index.php

索引.php

<iframe name="content" style="">
</iframe>
<form action="iframe_content.php" method="post" target="content">
<input type="text" name="Name" value="">
<input type="submit" name="Submit" value="Submit">
</form>

iframe_content.php

iframe_content.php

<?php
if (isset($_POST['Submit'])){
$Name = $_POST['Name'];
echo $Name;
}
?>

2.) AJAX

2.) AJAX

Index.php:

索引.php:

   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js">
    </script>
    <script type="text/javascript">
    function clickButton(){
    var name=document.getElementById('name').value;
    var descr=document.getElementById('descr').value;
    $.ajax({
            type:"post",
            url:"server_action.php",
            data: 
            {  
               'name' :name,
               'descr' :descr
            },
            cache:false,
            success: function (html) 
            {
               alert('Data Send');
               $('#msg').html(html);
            }
            });
            return false;
     }
    </script>
    <form >
    <input type="" name="name" id="name">
    <input type="" name="descr" id="descr">
    <input type="submit" name="" value="submit" onclick="return clickButton();">
    </form>
    <p id="msg"></p>

server_action.php

server_action.php

<?php 
$name = $_POST['name'];
$descr = $_POST['descr'];


echo $name;
echo $descr;

?>

Tags:phpajaxjqueryserversidehtml

标签: php ajax jquery serverside html

回答by Matas Lesinskas

This should solve your problem.
In this code after submit button click we call jquery ajax and we pass url to post
type POST/GET
data: data information you can select input fields or any other.
sucess: callback if everything is ok from server
function parameter text, html or json, response from server
in sucess you can write write warnings if data you got is in some kind of state and so on. or execute your code what to do next.

这应该可以解决您的问题。
在提交按钮单击后的这段代码中,我们调用 jquery ajax 并传递 url 来发布
类型 POST/GET
数据:数据信息您可以选择输入字段或任何其他字段。
成功:如果从服务器
函数参数文本、html 或 json 中一切正常,则回调,来自服务器的响应
成功,如果您获得的数据处于某种状态等,您可以编写警告。或执行您的代码下一步要做什么。

<form id='tip'>
Tip somebody: <input name="tip_email" id="tip_email" type="text" size="30" onfocus="tip_div(1);" onblur="tip_div(2);"/>
 <input type="submit" id="submit" value="Skicka Tips"/>
 <input type="hidden" id="ad_id" name="ad_id" />
 </form>
<script>
$( "#tip" ).submit(function( e ) {
    e.preventDefault();
    $.ajax({
        url: tip.php,
        type:'POST',
        data:
        {
            tip_email: $('#tip_email').val(),
            ad_id: $('#ad_id').val()
        },
        success: function(msg)
        {

            alert('Email Sent');
        }               
    });
});
</script>

回答by taufique

It's a must to take help of jquery-ajaxin this case. Without ajax, there is currently no solution.

jquery-ajax在这种情况下,必须寻求帮助。没有ajax,目前没有解决方案。

First, call a JavaScript function when the form is submitted. Just set onsubmit="func()". Even if the function is called, the default action of the submission would be performed. If it is performed there would be no way of stoping the page from refreshing or redirecting. So, next task is to prevent the default action. Insert the following line at the start of func().

首先,在提交表单时调用 JavaScript 函数。刚设置onsubmit="func()"。即使调用该函数,也会执行提交的默认操作。如果执行,将无法阻止页面刷新或重定向。因此,下一个任务是阻止默认操作。在 的开头插入以下行func()

event.preventDefault()

Now, there will be no redirecting or refreshing. So, you simply make an ajax call from func()and do whatever you want to do when call ends.

现在,不会有重定向或刷新。因此,您只需从 ajax 调用func()并在调用结束时做任何您想做的事情。

Example:

例子:

Form:

形式:

<form id="form-id" onsubmit="func()">
    <input id="input-id" type="text">
</form>

Javascript:

Javascript:

function func(){
    event.preventDefault();
    var newValue = $('#input-field-id').val();
    $.ajax({
        type: 'POST',
        url: '...',
        data: {...},
        datatype: 'JSON',
        success: function(data){...},
        error: function(){...},
    });
}

回答by Tyler

this is exactly how it CAN work without jQuery and AJAX and it's working very well using a simple iFrame. I LOVE IT, works in Opera10, FF3 and IE6. Thanks to some of the above posters pointing me the right direction, that's the only reason I am posting here:

这正是它可以在没有 jQuery 和 AJAX 的情况下工作的方式,并且使用简单的 iFrame 工作得很好。我喜欢它,适用于 Opera10、FF3 和 IE6。感谢上面的一些海报为我指明了正确的方向,这就是我在这里发帖的唯一原因:

<select name="aAddToPage[65654]" 
onchange="
    if (bCanAddMore) {
        addToPage(65654,this);
    }
    else {
        alert('Could not add another, wait until previous is added.'); 
        this.options[0].selected = true;
    };
" />
<option value="">Add to page..</option>
[more options with values here]</select>

<script type="text/javascript">
function addToPage(iProduct, oSelect){
    iPage = oSelect.options[oSelect.selectedIndex].value;
    if (iPage != "") {
        bCanAddMore = false;
        window.hiddenFrame.document.formFrame.iProduct.value = iProduct;
        window.hiddenFrame.document.formFrame.iAddToPage.value = iPage;
        window.hiddenFrame.document.formFrame.submit();
    }
}
var bCanAddMore = true;</script> 

<iframe name="hiddenFrame" style="display:none;" src="frame.php?p=addProductToPage" onload="bCanAddMore = true;"></iframe>

the php code generating the page that is being called above:

生成上面调用的页面的 php 代码:

if( $_GET['p'] == 'addProductToPage' ){  // hidden form processing
  if(!empty($_POST['iAddToPage'])) {
    //.. do something with it.. 
  }
  print('
    <html>
        <body>
            <form name="formFrame" id="formFrameId" style="display:none;" method="POST" action="frame.php?p=addProductToPage" >
                <input type="hidden" name="iProduct" value="" />
                <input type="hidden" name="iAddToPage" value="" />
            </form>
        </body>
    </html>
  ');
}

回答by wtaniguchi

You can try setting the target attribute of your form to a hidden iframe, so the page containing the form won't get reloaded.

您可以尝试将表单的 target 属性设置为隐藏的 iframe,这样包含该表单的页面就不会重新加载。

I tried it with file uploads (which we know can't be done via AJAX), and it worked beautifully.

我尝试了文件上传(我们知道不能通过 AJAX 完成),并且效果很好。

回答by DanC

Have you tried using an iFrame? No ajax, and the original page will not load.

您是否尝试过使用 iFrame?没有ajax,原始页面不会加载。

You can display the submit form as a separate page inside the iframe, and when it gets submitted the outer/container page will not reload. This solution will not make use of any kind of ajax.

您可以将提交表单显示为 iframe 内的一个单独页面,并且当它被提交时,外部/容器页面将不会重新加载。此解决方案不会使用任何类型的 ajax。