Javascript 如果php抛出警告,如何将数据从php发送到jQueryAjax成功处理程序?
我试图将数据从PHP发送到jQuery成功处理程序,然后再处理该数据 我只是通过phpJavascript 如果php抛出警告,如何将数据从php发送到jQueryAjax成功处理程序?,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我试图将数据从PHP发送到jQuery成功处理程序,然后再处理该数据 我只是通过phpecho来实现,然后在ajax成功处理程序响应文本中接收到echo字符串。这不是我的问题 PHP: JS: 上面的示例提示是。直到现在,一切都是完美的 我的问题是,假设PHP抛出任何警告,ajax成功响应文本将填充两个内容: 警告字符串 php回显字符串和js if条件 失败了 如果php发出任何警告,那么将数据从php发送到ajax成功处理程序的最佳成功方式是什么?对此您无能为力,因为您不希望php抛出某种错
echo
来实现,然后在ajax成功处理程序响应文本中接收到echo字符串。这不是我的问题
PHP:
JS:
上面的示例提示是。直到现在,一切都是完美的
我的问题是,假设PHP抛出任何警告,ajax成功响应文本将填充两个内容:
如果php发出任何警告,那么将数据从php发送到ajax成功处理程序的最佳成功方式是什么?对此您无能为力,因为您不希望php抛出某种错误消息,最好使用一些
if-else if…
梯形图
if (res == 'yes') {
alert(res);
} else if (res == 'no') {
alert('no');
} else {
alert('error');
}
附加一个错误处理程序,并将您的警告、错误和响应分离。最好从json执行,这样您就可以通过客户端过滤这两个错误
$response=array();
// A user-defined error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
global $response;
$err= "<b>Custom error:</b> [$errno] $errstr<br>";
$err.= " Error on line $errline in $errfile<br>";
$response['error']=$response['error'].PHP_EOL.$err;
}
// Set user-defined error handler function
set_error_handler("myErrorHandler");
//now your stuff
function function_name() {
global $response;
$Id = $_POST['id'];
if(/*condition*/){
$response['data']="yes";
echo $response['data'];
//better option
//echo json_encode($response); **get data and errors sepratly**
}
}
你没有
如果php端有错误或警告,这永远不会归结于响应
在正常的成功案例中,服务器返回HTTP 200 OK响应
在错误情况下,您应该捕获PHP警告和错误,并相应地将其与400/500管件匹配
然后不在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
...
}
}
});
如果您不想区分错误代码,可以使用:
现在让我们来处理PHP服务器端:
当然,您必须调整PHP以提供正确的响应,我强烈建议您使用经过良好测试的解决方案,例如。在您的成功案例中,这也将取代echo驱动的解决方案。你不妨研究一下这样的微框架,而不必重新发明轮子
我已经编写了一个非常基本的示例作为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();
<?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,
]
);
}
}
如果一切正常,请求服务器现在只会返回HTTP200OK响应
下面的例子使用的是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)"
}
如果您希望看到它的实际运行,那么首先,我建议您的php代码永远不要“抛出”错误或警告,并且您编写的任何代码都应该进行测试。我想你已经理解了这一部分,但我是为一位可能稍后到达这里的普通读者提到这一点的 错误或警告不应该是一般js应该依赖、检查或实现功能的条件。
然而,在开发理想的工作代码时,您可能希望缓冲输出,通过设置错误处理程序,您很可能可以检索缓冲输出并将其发送到js,希望是JSON。本地PHP警告、致命错误和通知永远不应该是最终用户关心的问题。这些类型的错误表明您使用了错误的东西,您应该修复它 但是,如果您正在谈论自己抛出异常,那么在这种情况下,您可以创建一个响应类来负责映射您的响应。对客户端的任何响应都应该是此类的实例。然后,创建一个新类exception,该类扩展原始exception,以便轻松抛出。向该类添加一个方法,该方法将异常数据转换为响应数据,并将其作为JSON进行回显
class MyResponse {
protected $code;
protected $response;
protected $isException;
protected $formFields;
/**
* Creates a NavResponse object that will be delivered to the browser.
*/
function __construct($code, $response = null, $field = false, $exception = false) {
$this->code = $code;
$this->formField = $field;
$this->response = $response;
$this->isException = $exception;
}
}
class MyException extends Exception {
function __construct($code, $log = null, $field = null) {
self::$exceptionThrown = true;
$this->_code = $code;
$this->_field = $field;
if ($log) {
// store log message.
}
}
public function response() {
return new MyResponse($this->_code, null, $this->_field, true);
}
}
您可以在php页面上添加errorhandler..@RohitKumar由于某些其他函数,警告已经存在。我的ajax调用正在正常工作并正确执行php函数。所以从技术上讲,我的ajax调用永远不会在错误处理程序中结束,因为它成功地执行了脚本。但当我提醒成功处理程序响应文本时,它会打印警告字符串以及php中的function.error\u处理程序的回显字符串,将处理出现的任何警告和错误。只有您必须在没有警告的情况下传递所需数据,或者为了更好的应用程序设计,请使用json来隔离警告/错误和数据。请检查下面的我的答案。我同意Sentinent,但不同意解决方案,因为它再次重新发明了轮子。有一些工具可以处理请求和响应,人们应该注意它们的可维护性,因为它们是可战斗的。@danish我已经更新了答案,包括一个基本的silex示例。
$ 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)"
}
class MyResponse {
protected $code;
protected $response;
protected $isException;
protected $formFields;
/**
* Creates a NavResponse object that will be delivered to the browser.
*/
function __construct($code, $response = null, $field = false, $exception = false) {
$this->code = $code;
$this->formField = $field;
$this->response = $response;
$this->isException = $exception;
}
}
class MyException extends Exception {
function __construct($code, $log = null, $field = null) {
self::$exceptionThrown = true;
$this->_code = $code;
$this->_field = $field;
if ($log) {
// store log message.
}
}
public function response() {
return new MyResponse($this->_code, null, $this->_field, true);
}
}