How to call a php script/function on a html button click(如何在 html 按钮单击时调用 php 脚本/函数)
问题描述
在有人攻击我或将其标记下来之前,我已经查看了整个互联网以了解如何执行此操作(包括 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";
?>
这篇关于如何在 html 按钮单击时调用 php 脚本/函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 html 按钮单击时调用 php 脚本/函数
基础教程推荐
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01