weixin_33721344 2016-01-09 13: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 12: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.

    展开全部

    评论
    编辑
    预览

    报告相同问题?

    悬赏问题

    • ¥15 PADS Logic 原理图
    • ¥15 PADS Logic 图标
    • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
    • ¥20 气象站点数据求取中~
    • ¥15 如何获取APP内弹出的网址链接
    • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
    手机看
    程序员都在用的中文IT技术交流社区

    程序员都在用的中文IT技术交流社区

    专业的中文 IT 技术社区,与千万技术人共成长

    专业的中文 IT 技术社区,与千万技术人共成长

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    客服 返回
    顶部