简体   繁体   English

使用Javascript onClick执行PHP功能而无需刷新页面

[英]Execute PHP function with Javascript onClick without page refresh

My research is pointing me to Ajax and/or JQuery, but I wanted to ask to make sure I understand and move in the right direction. 我的研究将我指向Ajax和/或JQuery,但我想问一下以确保我理解并朝着正确的方向发展。

I've been looking to use a javascript onclick function to create a popup(alert) asking to confirm that I want to proceed and show the changes I'm about to make. 我一直在寻找使用javascript onclick函数来创建一个弹出窗口(警告),要求确认我要继续并显示我将要进行的更改。

I hoped that I could use PHP $_POST or GET to echo the change in the popup/alert window. 我希望我可以使用PHP $ _POST或GET来回显弹出/警告窗口中的更改。 However without the page refresh it appears I can't do this, but looking for a confirmation? 但是,如果没有刷新页面,看来我无法执行此操作,但需要确认吗? Should I be looking for Ajax to do this? 我应该在寻找Ajax来做到这一点吗? Any thoughts/suggestions would likely give me a head start as php/ajax is sort of foreign to me. 任何想法/建议都可能使我先入为主,因为php / ajax对我来说有点陌生。

Sample code: 样例代码:

<script>     
function clicked() {
    if (confirm('Do you want to submit? <?php if(isset($_POST['city'])){$city = $_POST['city'];echo $city;}?>')) 
    {
        yourformelement.submit();
    } else {
        return false;
    }
}
</script>
</head>
<form action="output.php" method="post">
  <input name="city">

<input type="submit" onclick="clicked();" value="Button" />
 </form>

</html>

You can get the input value with jQuery before submitting: 您可以在提交之前使用jQuery获取输入值:

<form action="output.php" method="post" id="form">
    <input name="city" id="city_input">
    <input type="submit" value="Button" />
</form>
<script>     
    $('#form').submit(function(e) {
        e.preventDefault();
        let cityInputVal = $('#city_input').val();
        if (confirm('Do you want to submit ' + cityInputVal + '?')) 
        {
            this.submit();
        } else {
            return false;
        }
    });
</script>

The preventDefault() function stops the form submission and therefore, page refresh. preventDefault()函数停止表单提交,因此将刷新页面。

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

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