【问题标题】:Laravel 4 how to return multiple view data with ajax and json?Laravel 4 如何使用 ajax 和 json 返回多个视图数据?
【发布时间】:2013-12-09 02:08:29
【问题描述】:

基本上我正在尝试使用这个 ajax 制作一个弹出窗口:

$.ajax({
    type: 'GET'
    url: 'news/read'
    dataType: 'json'
    cache: false
    timeout: 10000
}).done (msg) ->
    $("article#pop-read").empty().html msg.view
    processing = false
    window.history.pushState
        path: msg.url
        , "", msg.url
    false

我正在返回一个视图值,它的 url 是这样的:

$data = json_encode(array(
        'view' => View::make('layouts.read'),
    'url' => 'news/read/2013/11/24/test-title-seperate-with-dash'
));
return $data;

这一切都很好,除了我无法从 laravel 获取视图值(它在 javascript 中返回 Object object)。但是如果我像return View::make('layouts.read') 那样直接写它,它会很好地返回。这是为什么呢?

另外(不必回答,不是主要问题),当我使用pushState 时,我的浏览器上的后退按钮不起作用,这是一个错误吗?

【问题讨论】:

    标签: php jquery ajax json laravel


    【解决方案1】:

    你可以试试这个

    $data = json_encode(array(
        'view' => (String)View::make('layouts.read'),
        'url' => 'news/read/2013/11/24/test-title-seperate-with-dash'
    ));
    return $data;
    

    你也可以使用

    View::make('layouts.read')->render();
    View::make('layouts.read')->__toString();
    

    另外,Laravel 出于同样的原因提供了Response::json() 方法(而不是json_encode)。

    【讨论】:

    • 好的,谢谢,所有解决方案都有效。现在转到pushState 问题。
    • 知道如何将视图解析为 json 响应吗?如何使用 $('#element').html(data.html) 将视图的 html 赋予页面中的元素?
    • 发布问题,给我链接,我会回答,具体问题中的细节。
    猜你喜欢
    • 1970-01-01
    • 2013-10-28
    • 2020-07-21
    • 2014-06-03
    • 2020-01-06
    • 2012-12-05
    • 2023-03-20
    • 2023-03-28
    • 2021-12-02
    相关资源
    最近更新 更多