POST Slim Route not working


POST Slim Route not working

我正在使用Slim进行开发。我所有的GET路由都运行良好,但每当我使用POST时,我都会得到"意外的结果"。请看一下我是如何实现slim和那个"意外错误"的。

index-routes.php(索引根文件)

<?php
require 'Slim/Slim.php';
'Slim'Slim::registerAutoloader();
$app = new 'Slim'Slim(array(
'debug' => true
));
require_once 'site-index.php';
require_once 'routes/default-routes.php';
$app->contentType('application/json');
$app->run();
?>

routes/default-routes.php

<?php
$app->post('/login',function(){
    echo 'AllHailSuccess!';
    })
?>

通过AJAX 调用POST请求的来源

function try1()
{
    var value1 = "afsfesa";
    API.call('/login','text','POST',function(data){console.log(data)},{var1:value1});
}

AJAX调用API

var API = {
  call:function(url,returnType,reqType,callback,data){
    var data = (!!data) ? data : {};
    var callback = (!!callback) ? callback : function(){};
    $.ajax({
      dataType: returnType,
      type:reqType,
      crossDomain: true,
      xhrFields: { withCredentials: true }, 
      url: url,
      data:data,
      success:callback,
      error:function(data){
          console.log("Error!");
        console.log(data);
      }
    });    
  }
}

"意外错误":当我执行try1()时,POST ROUTE确实会成功执行,但site-index.php(我在根index-routes.php文件中调用了它)的内容(整个纯文本代码)也会随之记录。我之所以首先导入site-index.php,是因为它就像我的网站的"主舞台"。这是我唯一想加载的页面,用户可以在其中导航

  • 我想知道:
    1. 为什么我会得到这种类型的输出
    2. 我的方法可以吗?我认为从索引路由导入我的主阶段文件是造成这种情况的原因。有其他方法吗

感谢您的帮助。非常感谢。

您的Slim调用将返回页面上显示的任何内容。

有几种方法可以解决这个问题:

  1. 将所有页面渲染嵌套在路由内,而不为AJAX路由渲染整个页面
  2. 修改AJAX调用以搜索返回的DOM来查找相关信息

在您显示的示例中,site-index.php 中的所有内容之后将显示AllHailSuccess!

许多人使用模板软件来呈现页面,然后使用服务通过模板来呈现页面。对于更基本的网站,我建议您创建一个简单的服务来显示内容。

以下是我在项目中使用的Viewer类的一个简单示例

class Viewer {
  /**
   * Display the specified filename using the main template
   * @param   string $filepath The full path of the file to display
   */
  public function display($filepath) {
    //set a default value for $body so the template doesn't get angry when $body is not assigned.
    $body = "";
    if (file_exists($filepath)) {
      $body = get_include_contents($filepath);
    } else {
      //You want to also return a HTTP Status Code 404 here.
      $body = get_include_contents('404.html');
    }
    //render the page in the layout
    include('layout.php');
  }
}
/**
 * Gets the contents of a file and 'pre-renders' it.
 * Basically, this is an include() that saves the output to variable instead of displaying it.
 */ 
function get_include_contents($filepath, $params = array()) {
  if (is_file($filepath)) {
    ob_start();
    include $filepath;
    $ret = ob_get_contents();
    ob_end_clean();
    return $ret;
  }
  return false;
}

您想要向用户显示页面布局的路线现在应该是这样的:

$app->get('/', function() {
  (new Viewer())->display('home.html');
});

这绝不是一个全面的解决方案,因为它没有处理正确的HTTP状态代码,并且文件在代码中直接引用,这可能会变得很混乱,但这是一个很好的起点,它可以快速模拟类似的东西。

如果您想继续这个方向,我建议您查看Slim v2响应文档,并创建一个构造和返回响应对象的类。这将为您提供更多的灵活性和设置HTTP状态代码和HTTP返回头的能力。

我强烈建议您也查看Slim v3响应,因为Slim 3使用PSR-7响应对象,这是跨多个框架的标准对象。