使用PHP调用JavaScript [英] Calling JavaScript with PHP

查看:125
本文介绍了使用PHP调用JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在按下按钮时调用一个PHP函数,例如:

I want to call a PHP function when pressing on a button, sort of like:

<?php 
function output(){
  // do something
}
?>

<input type="button" value="Enter" onclick="output()"/>

我试图做成这样:

I tried to make something like:

<input type="button" value="Enter" onclick="test.php?execute=1"/>

其中test.php是当前页面,然后是php

where test.php is current page and then by php

<? if(isset(&execute)){ echo "Hello"; } ?>

但它不起作用。

推荐答案

我认为使用AJAX调用可以做你想问的问题。我不太了解PHP,但您可以使用下面的示例,并将您传递到服务器的数据添加到另一个变量中,以指示要在服务器上调用哪个函数。在服务器上,您可以添加一些IF语句,这些语句将根据传入的名称调用某个函数并返回结果。

I think using an AJAX call would do sort of what you are asking. I don't know PHP very well but you can use the following example, and add another variable with the data you are passing in to the server to indicate which function you want to call on the server. On the server you can add some "IF" statements that will call a certain function based on the name passed in and return the result.

以下是您可以使用的在您的JavaScript客户端中使用 jQuery库作为帮助进行AJAX调用:

Here is what you could use on in your javascript client using the jQuery library as a helper to do the AJAX call:

    <input type="button" value="Enter" onclick="output()"/>
    <script type="text/javascript">
function output(){
    $.ajax({
        type: "POST",
        url: "submit_data.php",
        data:   "username=" + "SomeUser" 
        +   "&email=" + "someEmail@google.com"
                    +       "&functionName=" + "theFunction1",
        success: function(html){
            alert('sucess!  Result is:' + html);
        }
    });

    }   
</script>

,您可以使用这样的代码来捕获您的javascript传入的数据。你会想把这个文件名叫做submit_data.php来匹配上面的javascript:

and you can use code such as this to catch the data your javascript is passing in. In this example you would want to call this file name as "submit_data.php" to match the javascript above:

<?php

    // Variables

    $Username = $_POST['username'];
    $Email    = $_POST['email'];    
    $FunctionName = $_POST['functionName'];

    //Add code here to choose what function to call and echo the result
    // If $FunctionName equals 'theFunction1' then execute theFunction1
    // If $FunctionName equals 'theFunction2' then execute theFunction2

    echo "You called A Page!";

?> 

在这里,我没有对用户名和电子邮件进行简单的抓取并将它们存入持有变量。但是你可以在这里轻松添加额外的功能,比如检查你想运行的函数的名字。

Here I am doing nothing with the "username" and "email" simply grabbing it and storing them into holding variables. But you can easily add extra functionality here, such as checking for a name of a function that you want to run.

这篇关于使用PHP调用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆