简体   繁体   English

在ajax中执行php文件

[英]Execute php file in ajax

I have this php file:我有这个 php 文件:

<?

function bb(){
system( 'python my_script.py');
echo "done";
}

bb();
?>

I would like to execute this, using ajax.我想使用 ajax 执行此操作。 I do it this way:我这样做:

<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
          data : { },
          url  : 'action.php',              // <=== CALL THE PHP FUNCTION HERE.
          success: function ( data ) {
            alert( data );               // <=== VALUE RETURNED FROM FUNCTION.
          },
          error: function ( xhr ) {
            alert( "error" );
          }
        });
}
    </script>

This is executed when a button is clicked:这是在单击按钮时执行的:

<button type="button" class="btn btn-outline-danger" onclick="myAjax()">Primary</button>

The problem is that i get always error case.问题是我总是遇到错误情况。 Even if my php file should execute only echo (ie deleting system).即使我的 php 文件应该只执行 echo(即删除系统)。 How can i solve that?我该如何解决?

Using Chrome inspector, under Network tab i get this error:使用 Chrome 检查器,在网络选项卡下,我收到此错误:

jquery.js:4 XMLHttpRequest cannot load file:///Users/Antonio/Desktop/script/action.php.Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

but the file is accessible using this path.但是可以使用此路径访问该文件。

Seeing file:///Users/Antonio/Desktop/script/action.php , I assume you are running your HTML file directly from the local file system.看到file:///Users/Antonio/Desktop/script/action.php ,我假设您直接从本地文件系统运行 HTML 文件。

In this case the, for security reasons, browser doesn't allow access to your local files.在这种情况下,出于安全原因,浏览器不允许访问您的本地文件。
Even if it did, the PHP file wouldn't be executed.即使这样做了,PHP 文件也不会被执行。

To fix those two issues, you need to run your own local HTTP server, which would execute your PHP files and be accessed through the HTTP protocol.要解决这两个问题,您需要运行自己的本地 HTTP 服务器,该服务器将执行您的 PHP 文件并通过 HTTP 协议进行访问。

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

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