简体   繁体   English

如何在onclick事件中执行PHP函数?

[英]How do I execute a PHP function in an onclick event?

I have some HTML files, and what I want to do, is put something like the following, inside the <head> section of the html document: 我有一些HTML文件,我想要做的是,在html文档的<head>部分内放置如下内容:

<script href="myphpfile.php" />

and then somewhere on my page, I want to call a PHP function from an onclick event, like so: 然后我的页面上的某个地方,我想从onclick事件调用PHP函数,如下所示:

<a onclick="performPhpFunction();" href="javascript:void(0);">Do something</a>

How can I do this? 我怎样才能做到这一点?

I don't know why, but when searching for a solution tonight, I cannot seem to find one, and I have seen this many times, but forgot how it was done, and now I don't remember which websites I saw it on. 我不知道为什么,但今晚寻找解决方案的时候,我似乎找不到一个,我已经看过很多次了,但是忘记了它是怎么做的,现在我不记得我看过哪个网站了。

You can load the PHP File over AJAX with JS 您可以使用JS通过AJAX加载PHP文件

jQuery jQuery的

$("#link").click(function(){
      $.ajax({
           url: "myphpfile.php"
      });
});

Umm....PHP doesn't work this way. 嗯.... PHP不会这样工作。 PHP is server-side. PHP是服务器端的。 You cannot directly call PHP functions from an onclick hander. 你不能直接从onclick hander调用PHP函数。 That only can call javascript (which is client-code) code. 那只能调用javascript(即客户端代码)代码。 What you can do is call the PHP function via an AJAX GET call. 你可以做的是通过AJAX GET调用调用PHP函数。

You can't call PHP functions from javascript directly. 你不能直接从javascript调用PHP函数。 You can either use AJAX to call back to a PHP page that does what you want, like Rocket and Fincha have said or you can get PHP to output the javascript, and change it based on what the user sends to you. 您可以使用AJAX回调到您想要的PHP页面,例如Rocket和Fincha所说的,或者您可以让PHP输出javascript,并根据用户发送给您的内容进行更改。

To do the latter; 做后者; in the PHP file you'll need a line like 在PHP文件中你需要一行代码

<?php

header('Content-type: text/javascript');

?>

And that has to be BEFORE you output anything. 而且必须在你输出任何东西之前。

Then below that you generate the javascript, as you would any javascript file, but you can use server side data and include it in your file. 然后在下面生成javascript,就像你的任何javascript文件一样,但你可以使用服务器端数据并将其包含在你的文件中。

function AJavascriptFunction()
{
    alert(<?= $_GET['getvar'] ?>);
}

Then in your html or PHP page you can do 然后在你的html或PHP页面中你可以做到

<a onclick="AJavascriptFunction();" href="javascript:void(0);">Do something</a>

I do not recommend this. 我不推荐这个。 Use AJAX 使用AJAX

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

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