通过JQuery ajax执行PHP函数

问题描述:

I know it is not possible to simply call a function through ajax. As it only sends data via HTTP headers. However, I am trying to achieve something. I'm trying to execute a piece of PHP code, by the click of a button. The code consists of a shell_exec("omxplayer file.mp3") So my ultimate goal is, to have a page load, display a button, which in turn, once clicked, will execute this piece of code (shell command).

I have looked for solutions and have not found one, even though there have been a lot of questions asked with a similar title to mine.

How can I achieve this concept?

EDIT: My ultimate goal is to use the shell_exec() to start playing a file using omxplayer on a linux machine.

我知道不可能简单地通过ajax调用函数。 因为它只通过HTTP标头发送数据。 但是,我正在努力实现一些目标。 我正在尝试通过单击按钮执行一段PHP代码。 代码由 shell_exec(“omxplayer file.mp3”) code> 组成。我的最终目标是,为了加载页面,显示一个按钮,反过来,一旦点击,将执行这个 代码(shell命令)。 p>

我已经找到了解决方案而没有找到解决方案,尽管有很多问题与我的问题类似。 p> \ n

我如何实现这个概念? p>

编辑:我的最终目标是使用 shell_exec() code>开始播放 在linux机器上使用omxplayer的文件。 strong> p> div>

You can use .get()

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $("button").click(function() {
        $.get("script.php?code=myFunction", function(data, status) {
            alert("Data: " + data + "
Status: " + status);
        });
    });
});
</script>
</head>
<body>
    <button>Execute Command</button>
</body>
</html>

script.php

if (!empty($_GET['code']) {
    $output = shell_exec(<do shell command here>):
    echo $output;
}

The following assumes that xxx is your PHP file and output is the response from the xxx file:

button.onclick = function() {
    $.ajax({
        url: '/my/site/xxx.php',
        data: {action: 'test'},
        type: 'post',
        success: function(output) {
            alert(output);
        }
    });
};

You are looking at things the wrong way.

Create a separate page that executes the exec command and displays the result.

Create an interface page where - and you have a wide choice of options - when the user clicks a button you send him to the exec page.

I'm assuming you need or want to feed data to the exec command. The page with the exec command can process values sent using GET and more securely POST (or REQUEST) Just like any other html form would.

If you want to create a somewhat modern feel to an old school browser bash implementation you have a few options.

  1. Submit onto self. Every time you submit the page will be redrawn with the new data and the new exec will have run.

  2. Submit into a target iframe. The interface will linger, the iframe will update the contents.

  3. xhtmlhttp post (asynchronous or "ajax" even though it doesn't have to be) and update the contents of a div with the response - from a separate php page.