我正在尝试将数据从 PHP 发送到 jQuery 成功处理程序,然后再处理该数据。
我只是通过 php echo
完成了它,然后在 ajax 成功处理程序响应文本中收到了 echo 字符串。这不是我的问题。
PHP:
function function_name() {
$Id = $_POST['id'];
if(/*condition*/){
echo "yes";
}
}
JS:
$.ajax({
type:'POST',
data:{action:'function_name', id:ID},
url: URL,
success: function(res) {
if(res == 'yes'){
alert(res);
}
}
});
上面的例子提示是。到目前为止,一切都很完美。
我的问题是假设如果 PHP 抛出任何警告,ajax 成功响应文本将填充两件事:
- 警告字符串
- php 回显字符串和 js if 条件 失败。
如果有来自 php 的任何警告,从 php 向 ajax 成功处理程序发送数据的最佳成功方法是什么?
最佳答案
你不知道。
如果 php 端出现错误或警告,这永远不应该归结为响应。
在正常的成功案例中,您的服务器会返回 HTTP 200 OK 响应。
在错误情况下,您应该捕获 PHP 警告和错误并将其相应地匹配到合适的 400/500 HTTP error code .
然后您不在 success
方法中处理这种情况,而是在适当的错误回调中处理。
让我们从 JavaScript 开始:
这是我如何处理这种情况的示例:
$.ajax({
type: "POST",
url: url,
data: $form.serialize(),
success: function(xhr) {
//everything ok
},
statusCode: {
400: function(xhr, data, error) {
/**
* Wrong form data, reload form with errors
*/
...
},
409: function(xhr, data, error) {
// conflict
...
}
}
});
如果您对区分错误代码不感兴趣,可以使用 this pattern instead :
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 component .这也应该取代您成功案例中的 echo 驱动解决方案。您不妨研究像 Silex 这样的微框架。那do the bulk of the HTTP request/response handling already for you无需重新发明轮子。
我已经编写了一个非常基本的示例作为 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;
/**
* IndexController
**/
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 --form POST http://localhost:1337 data="hello world"
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 --form POST http://localhost:1337
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 --form GET http://localhost:1337 data="hello world"
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)"
}
如果您想实际查看它,feel free to check it out on github .
关于javascript - 如果 php 抛出警告,如何将数据从 php 发送到 jquery ajax 成功处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33123957/