简体   繁体   English

使用Ajax请求执行PHP文件

[英]Executing a PHP file using Ajax request

Still grasping Ajax, so I beg your patience. 仍然抓住Ajax,所以我请耐心等待。 I am trying to run a php file from within javascript using an ajax call with the help of jQuery. 我试图在javascript的帮助下使用ajax调用从javascript中运行一个php文件。 I do not need to GET / POST any data, I just intent the PHP code to be executed and the message 'hello world' logged to the console (I intend to use this in a button with an onclick() function). 我不需要GET / POST任何数据,我只是想要执行PHP代码并将消息'hello world'记录到控制台(我打算在带有onclick()函数的按钮中使用它)。 The only thing that gets logged is the "success" message. 唯一记录的是“成功”消息。 I want the PHP code to execute without leaving the current page, but I think I may be missing how AJAX works. 我希望PHP代码在不离开当前页面的情况下执行,但我想我可能会错过AJAX的工作原理。 Or perhaps there is a better way to accomplish this. 或者也许有更好的方法来实现这一目标。 Thanks for helping out. 谢谢你的帮助。

PS: I can see the resource "ajax.php" is being loaded as a XHR, by using Safari's web developer tools. PS:通过使用Safari的Web开发人员工具,我可以看到资源“ajax.php”正在作为XHR加载。

Content of the index file that calls ajax.php is: 调用ajax.php的索引文件的内容是:

<script>
$.ajax({
  url : 'action/ajax.php',
  type : 'POST',
  success : function (result) {
    console.log ('success');
  },
  error : function () {
    console.log ('error');
  }
});
</script>

Content of ajax.php is: ajax.php的内容是:

<?php
echo '<script>console.log("hello world");</script>';
?>

Appreciate that you are taking initiative to learn PHP, jQuery and AJAX. 感谢您主动学习PHP,jQuery和AJAX。

Just some modifications and you are on track: 只需进行一些修改,您就可以了:

Javascript (jQuery): Javascript(jQuery):

<script>
   $.ajax({

     url : 'action/ajax.php',
     type : 'POST',
     success : function (result) {
        console.log (result); // Here, you need to use response by PHP file.
     },
     error : function () {
        console.log ('error');
     }

   });
</script>

Content of ajax.php is: ajax.php的内容是:

<?php
    //echo '<script>console.log("hello world");</script>';
    // Change above line to:
    echo "hello world";
?>

Your data is stored in callback function 您的数据存储在回调函数中

<script>
 $.ajax({
  url : 'action/ajax.php',
type : 'POST',
 success : function (result) {
 //this is where you need to call your data which is result and not success
 console.log (result);
 },
error : function () {
 console.log ('error');
 }
 });
</script>

You need to execute the returned javascript if you want it to run 如果要运行,则需要执行返回的javascript

success : function (result) {
    eval(result); //run the result code
    console.log ('success');
},

Content of ajax.php will now be: ajax.php的内容现在是:

<?php
   echo 'console.log("hello world")';
?>

But then you nead clean JS without the script tag 但是你没有script标签就干净了JS

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

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