简体   繁体   中英

Execute php file in ajax

I have this php file:

<?

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

bb();
?>

I would like to execute this, using 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). How can i solve that?

Using Chrome inspector, under Network tab i get this error:

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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