如何仅从PHP AJAX调用返回返回的变量?

时间:2017-03-19 14:58:49

标签: php jquery ajax

我最近按照本指南创建了一个CMS系统:

http://requiremind.com/a-most-simple-php-mvc-beginners-tutorial/

但是我在PHP页面中使用AJAX调用时遇到了问题。当向控制器方法发送post请求时,返回的数据包括layout.php html数据,其中我真正想要的是回显的PHP变量。

layout.php文件:

<?php
<DOCTYPE html><head>

    <title>Stack overflow question</title>
  </head>

  <body>

    <!-- pulls in the relevant page -->
    <?php require_once('routes.php'); ?>

  <body>

<html>
?>

routes.php文件:

<?php
  function call($controller, $action) {
// require the file that matches the controller name
require_once('controllers/' . $controller . '_controller.php');

// create a new instance of the needed controller
switch($controller) {
  case 'pages':
    $controller = new PagesController();
  break;
  case 'controller':
    $controller = new controller();
  break;

}

// call the action
$controller->{ $action }();
  }

  // just a list of the controllers we have and their actions
  // we consider those "allowed" values
  $controllers = array('pages' => ['error'],
                   'controller' => ['getapostervariable', 'openpage']);

  // check that the requested controller and action are both allowed
  // if someone tries to access something else he will be redirected to the error action of the pages controller
  //checking if the controller variable is contained within the controllers array.
  if (array_key_exists($controller, $controllers)) {
  //checking to see if the action is available in the controllers array at the point of the controller key
if (in_array($action, $controllers[$controller])) {
  call($controller, $action);
    } else {
  call('pages', 'error');
}
  } else {
call('pages', 'error');
  }
 ?>

例如,如果我有一个控制器:

class controller{

   public static function openpage(){
      require_once(page.php);
   }

   public static function getapostedvariable(){
      require_once(page.php);
      $string = $_POST['string'];
      echo $string;
   }
}

和一个AJAX请求:

$.post("http://site/index.php?controller=controller&action=getapostedvariable",
{
    string: "hello there"
},
function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
});

它返回父php页面(layout.php使用require_once包含带有ajax请求的页面)和我的php变量$ string在该页面的body标签内。

我只是想知道是否有可能只在ajax响应中接收php变量/我该怎么做?

0 个答案:

没有答案