【问题标题】:AJAX request in Laravel and ASCII response issueLaravel 中的 AJAX 请求和 ASCII 响应问题
【发布时间】:2014-06-20 22:57:28
【问题描述】:

我有一个使用 AJAX 请求的 Laravel 应用程序。

在其中一个请求中,我必须使用波斯字母(非拉丁)字符的 JSON 响应 AJAX 请求。

使用这种内容类型,传统 PHP 已经为我解决了这个问题:

"应用程序/json; charse=utf-8"

而且它有效。

但在 Laravel 中,它发送 ASCII 版本的波斯字母,如下所示:

46 \u0646\u0645\u0648\u0646\u0647 \u0645\u062a\u0646 \u0646\u0645\u0648\u0646\u0647 \u0645\u062a\u0646 \u0646\u0645\u0648\u0646\u0647 \u0645\u062a\u0646 \u0646\u0645\u0648\u0646\u0647 \u0645\u062a\u0646 \u0646\u0645\

我无法在 Laravel 中找到解决方案。

我在 Laravel 的视图中是这样发送的:

$.ajax({
                   url : "<?php echo url("/ajax"); ?>",
                   data : { id : $(this).find("input[type='hidden']").val()},
                    cache : 'no-cache',
                    type : 'POST',
                    success : function(response){
                        console.log(response);
                    },
                });

还有路由器:

Route::post("ajax", function(){
    header("ContentType=application/json; charset=utf-8");
    $res = Image::find(Req::id())->toArray();
    echo json_encode($res);
});

结果就是上面打印的ASCII字符。

我该怎么办?我猜的一个问题是,在 Laravel 中,很多事情都会在解释器到达路由器之前发生,因此设置标头可能需要一些配置或技巧。

【问题讨论】:

    标签: php jquery ajax json laravel


    【解决方案1】:

    您可能需要使用响应类返回 json。

    Route::post('ajax', function()
    {
        $headers = array(
            'ContentType' => 'application/json',
            'charset' => 'utf-8',
        );
    
        $res = Image::find(Req::id());
    
        return Response::json($res, 200, $headers);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      • 2015-08-07
      • 2017-10-19
      • 1970-01-01
      • 2015-03-18
      相关资源
      最近更新 更多