weixin_33721344 2016-01-09 21:22 采纳率: 0%
浏览 25

POST Slim Route不起作用

I'm using Slim for development. All my GET routes are working just fine, but whenever I use POST, I get "unexpected result". Please have a look at how I've implemented slim and that "unexpected error".

index-routes.php (index root file)

<?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!';
    })
?>

origin of POST request called via AJAX

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

AJAX Call 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);
      }
    });    
  }
}

"Unexpected error": When I execute try1(), THE POST ROUTE DOES GETS EXECUTED SUCCESSFULLY but the contents (The entire code in plain-text) of site-index.php (Which I called in root index-routes.php file) also gets logged along with it. The reason why I imported site-index.php in the first place, is because it acts like a "main stage" for my site. It's the only page I want to load and user navigates within it.

  • I want to know:
    1. Why I'm getting this type of output?
    2. Is my approach alright? I think importing my main-stage file from index- routes is causing this. Is there any other way of doing this?

Any help is appreciated. Thank you.

  • 写回答

1条回答 默认 最新

  • weixin_33743880 2016-01-14 20:19
    关注

    Your Slim calls are going to return anything that is displayed on the page.

    There are a few ways to work around this:

    1. Nest all of your page renders inside the route and don't render full pages for AJAX routes.
    2. Modify your AJAX calls to search the returned DOM to find the relevant information.

    In your example shown, AllHailSuccess! will be displayed after all of the content in site-index.php

    Many people use templating software to render their pages and then use a service to render their page via the template. For more basic sites, I would recommend you create a simple service to display content.

    Here's a simple example of a Viewer class I use in my project(s)

    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;
    }
    

    Your routes that you want to display the page layout to the user should look something like this now:

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

    This is by no means a comprehensive solution because it does not address proper HTTP status codes and files are referenced directly in your code which can get messy, but it's a good starting point and its quick to mock something like this up.

    If you want to continue in this direction, I would recommend you take a look at the Slim v2 Response Documentation and create a class that constructs and returns Response objects. This would give you much more flexibility and power to set HTTP status codes and HTTP Return headers.

    I highly recommend checking out Slim v3 Responses as well because Slim 3 uses PSR-7 Response objects which are standard across multiple frameworks.

    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改