ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript – 如果php发送警告,如何从php发送数据到jquery ajax成功处理程序?

2019-05-28 06:16:50  阅读:179  来源: 互联网

标签:jquery php javascript ajax


我正在尝试将数据从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 echo string,因此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.在您的成功案例中,这也应该取代您的回声驱动解决方案.你不妨看看像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 /哥白尼/控制器/ 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.

标签:jquery,php,javascript,ajax
来源: https://codeday.me/bug/20190528/1168849.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有