如何在 html 按钮单击时调用 php 脚本/函数

2022-01-09 00:00:00 onclick php ajax

在有人攻击我或将其标记下来之前,我已经查看了整个互联网以了解如何执行此操作(包括 stackoverflow 上的相同问题).我是新手,我发现学习新概念非常困难,所以请放轻松.

Before someone has a go at me or marks this down, I have looked all over the internet to find out how to do this (including the same question on stackoverflow). I'm new, and I am finding it very hard to learn new concepts so please be easy on me.

我想要做的是在单击按钮时调用 php 脚本/函数.如果有帮助,我会在 WAMP 中运行它.这是我的代码:

What I want to do is call a php script/function on a button click. I have this running in WAMP if that helps. Here's my code:

<?php include 'the_script.php'; ?>

<button type="button" onclick="the_function()">Click Me</button>

the_script.php 里面有这个:

the_script.php has this in it:

the_function() {
    echo "You win";
}

为什么这不起作用?我听说按钮是客户端等,而 PHP 是服务器端,这意味着您不能将两者链接在一起.我知道你必须使用 AJAX 来完成这项工作,但是我完全不知道如何去做.我试过用谷歌搜索它等等,但是我什么也找不到.我知道如何使用 AJAX 并用它调用事件,但是我仍然不知道如何让它调用 PHP 脚本.

Why isn't this working? I've heard about the button being client side etc. and PHP being server-side, which means that you cannot link the two together. I know that you have to use AJAX to make this work, however I legitimately have absolutely no clue how to do it. I've tried googling it etc., however I can't find anything. I know how to use AJAX and call events with it, however I still have no idea how to make it call a PHP script.

你能否让你的答案尽可能简单明了,我是新手

Can you please make your answers as clear and simple as possible, I'm new to this

感谢您的帮助:)

编辑***

出于某种原因,无论我走到哪里,每个人的代码都是不同的.我学习 AJAX 的方式看起来完全不同.你能这样写,让我明白吗?谢谢,这是一个例子:

For some reason wherever I go everyone's code is different. The way I have been taught AJAX looks completely different. Can you please write it this way so I can understand? Thanks, here's an example:

var request;

if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
} else {
    request = new ActiveXObject("Microsoft.XMLHTTP");
}

request.open('GET', 'file.php', true);

request.onreadystatechange = function() {

    if (request.readyState===4 && request.status===200) {
        do stuff
    }
}

request.send();

推荐答案

试试这个:

<button type="button">Click Me</button>
<p></p>
<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){

            $.ajax({
                type: 'POST',
                url: 'script.php',
                success: function(data) {
                    alert(data);
                    $("p").text(data);

                }
            });
   });
});
</script>

在script.php中

In script.php

<?php 
  echo "You win";
 ?>

相关文章