jQuery ajax() POST to Slim PHP framework

匆匆过客 提交于 2020-01-22 12:57:48

问题


Using jquery mobile+phonegap, trying to POST to a Slim application, I have this code:

$( document ).on( "vclick", "#test_form", function() {
            $.ajax({
                type: "POST",
                url: "http://mydomain.com/slim/",
                crossDomain: true,
                beforeSend: function() {
                    $.mobile.loading('show')
                },
                complete: function() {
                    $.mobile.loading('hide')
                },
                data: {namec:$("#namec").val()},
                dataType: 'json',
                success: function(response) {
                    //console.error(JSON.stringify(response));
                    alert(response);
                },
                error: function() {
                    //console.error("error");
                    alert('Not working!');
                }
            });
});

I have tested this with other non Slim PHP pages and everything works fine, I get the ajax error with Slim though.

My Slim app:

<?php
require 'Slim/Slim.php';

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->post('/', function () {
    echo json_encode($_POST("namec"));
});

$app->run();

Just started using Slim, so not sure what I could be doing wrong.


回答1:


Have you tried:

$app->post('/', function() use ($app) {
       // ...
       $req = $app->request();
       echo json_encode($req->post('namec'));
       //...
}

Also this page should help




回答2:


As per slim v3 you can access the request object with $request->getParams()

$app->get('/', function (Request $request, Response $response){
   $data = $request->getParams()
   echo json_encode($data['namec']);
}

see documentation here https://www.slimframework.com/docs/v3/objects/request.html#route-object



来源:https://stackoverflow.com/questions/17015473/jquery-ajax-post-to-slim-php-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!