.
php , .
HTTP 200 OK.
PHP 400/500 HTTP.
success
, .
. JavaScript:
, :
$.ajax({
type: "POST",
url: url,
data: $form.serialize(),
success: function(xhr) {
},
statusCode: {
400: function(xhr, data, error) {
...
},
409: function(xhr, data, error) {
...
}
}
});
, :
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "YOUR ERROR HANDLING" );
})
.always(function() {
alert( "finished" );
});
PHP:
, , PHP , , . symfony2 HTTP Kernel. - . , Silex, HTTP-/ , .
silex, :
index.php
:
<?php
use Kopernikus\Controller\IndexController;
require_once __DIR__ . '/vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
$className = IndexController::class;
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app['controller.index'] = $app->share(
function () use ($app) {
return new IndexController();
}
);
$app->post('/', "controller.index:indexAction");
$app->error(
function (\Exception $e, $code) {
switch ($code) {
case 404:
$message = 'The requested page could not be found.';
break;
default:
$message = $e->getMessage();
}
return new JsonResponse(
[
'message' => $message,
]
);
}
);
$app->run();
src/Kopernikus/Controller/IndexController.php
:
<?php
namespace Kopernikus\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class IndexController
{
public function indexAction(Request $request)
{
$data = $request->request->get('data');
if ($data === null) {
throw new BadRequestHttpException('Data parameter required');
}
return new JsonResponse(
[
'message' => $data,
]
);
}
}
HTTP 200 OK, .
httpie, curl.
:
$ http
HTTP/1.1 200 OK
Cache-Control: no-cache
Connection: close
Content-Type: application/json
Date: Wed, 14 Oct 2015 15:37:30 GMT
Host: localhost:1337
X-Powered-By: PHP/5.5.9-1ubuntu4.13
{
"message": "hello world"
}
:
, :
$ http
HTTP/1.1 400 Bad Request
Cache-Control: no-cache
Connection: close
Content-Type: application/json
Date: Wed, 14 Oct 2015 15:37:00 GMT
Host: localhost:1337
X-Powered-By: PHP/5.5.9-1ubuntu4.13
{
"message": "Data parameter required"
}
:
$ http
HTTP/1.1 405 Method Not Allowed
Allow: POST
Cache-Control: no-cache
Connection: close
Content-Type: application/json
Date: Wed, 14 Oct 2015 15:38:40 GMT
Host: localhost:1337
X-Powered-By: PHP/5.5.9-1ubuntu4.13
{
"message": "No route found for \"GET /\": Method Not Allowed (Allow: POST)"
}
, github.