Javascript 如何从 Laravel 5 中的 AJAX 调用返回视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28634712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:09:28  来源:igfitidea点击:

How can I return a view from an AJAX call in Laravel 5?

javascriptphpjqueryajaxlaravel

提问by Chris Hymanson

I'm trying to get an html table to return on an ajax call.

我正在尝试获取一个 html 表以在 ajax 调用时返回。

route:

路线:

Route::post('job/userjobs', 'JobController@userjobs');  

ajax on calling page:

调用页面上的ajax:

function getUserJobs(userid) {
    $_token = "{{ csrf_token() }}";
    var userid = userid;
    $.ajax({
        headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') },
        url: "{{ url('/job/userjobs') }}",
        type: 'POST',
        cache: false,
        data: { 'userid': userid, '_token': $_token }, //see the $_token
        datatype: 'html',
        beforeSend: function() {
            //something before send
        },
        success: function(data) {
            console.log('success');
            console.log(data);
            //success
            //var data = $.parseJSON(data);
            if(data.success == true) {
              //user_jobs div defined on page
              $('#user_jobs').html(data.html);
            } else {
              $('#user_jobs').html(data.html + '{{ $user->username }}');
            }
        },
        error: function(xhr,textStatus,thrownError) {
            alert(xhr + "\n" + textStatus + "\n" + thrownError);
        }
    });
}



//on page load
getUserJobs("{{ $user->id }}");

controller:

控制器:

public function userjobs() {
    $input = Request::all();
    if(Request::isMethod('post') && Request::ajax()) {
        if($input['userid']) {
            $userjobs = Userjob::select('select * from user_jobs where user_id = ?', array($input['userid']));
            if(! $userjobs) {
                return response()->json( array('success' => false, 'html'=>'No Jobs assigned to ') );
            }
            $returnHTML = view('job.userjobs')->with('userjobs', $userjobs);
            return response()->json( array('success' => true, 'html'=>$returnHTML) );

        }
    }   
}

view:

看法:

@section('content')
<table class="table table-striped">
    <tbody>
@foreach ($userjobs as $userjob)
        <tr>
            <td><strong>{{ $userjob->title }}</strong><br />
            {{ $userjob->description }}
            </td>
        </tr>
@endforeach
</table>
@stop

Im not getting anything in the json.html data. nothing. If in the controller I say:

我在 json.html 数据中没有得到任何东西。没有。如果在控制器中我说:

return response()->json( array('success' => true, 'html'=>'<span>html here</html>') );

This works just fine.

这工作得很好。

How can I return a view from an ajax call in Laravel 5.

如何从 Laravel 5 中的 ajax 调用返回视图。

回答by lukasgeiter

The view()function just creates an instance of the Viewclass. Not just an HTML string. For that you should call render():

view()函数只是创建View类的一个实例。不仅仅是一个 HTML 字符串。为此,您应该致电render()

$returnHTML = view('job.userjobs')->with('userjobs', $userjobs)->render();
return response()->json(array('success' => true, 'html'=>$returnHTML));

回答by Jorn

$returnHTML = view('job.userjobs')->with('userjobs', $userjobs)->renderSections()['content'];

So this question is old and the most upvoted answer did not solve the problem for the asker and for me neither. I ran into the same problem and it took me two days to find the solution. Everywhere I came looking for answers the said use ->render(). But nothing returned. I have a partial view which I wanted to include. I had not extended my partial view or given it a section name. Since this is not necessary when including it inside a blade file with the include directive.

所以这个问题很老了,最受好评的答案并没有解决提问者和我的问题。我遇到了同样的问题,我花了两天时间才找到解决方案。我到处寻找上述用途的答案->render()。但什么都没有回来。我有一个我想包括的局部视图。我没有扩展我的部分视图或给它一个部分名称。因为在使用 include 指令将其包含在刀片文件中时,这不是必需的。

So the solution is, enclose your html inside a section and instead of render(), use renderSections()['sectionname']. Just using render()will not work.

所以解决方案是,将您的 html 包含在一个部分中,而不是render()使用renderSections()['sectionname']. 仅仅使用是render()行不通的。

I hope this will safe somebody some time and frustration!

我希望这可以让某人安全一些时间和沮丧!

回答by Imtiaz Pabel

use string function before view file name like as

在查看文件名之前使用字符串函数,如

return (String) view('Company.allUserAjax');

回答by Maky

if your ajax is correct and you are getting results from your DB

如果您的 ajax 是正确的并且您正在从您的数据库中获得结果

 $returnHTML = view('job.userjobs',[' userjobs'=> $userjobs])->render();// or method that you prefere to return data + RENDER is the key here
            return response()->json( array('success' => true, 'html'=>$returnHTML) );

回答by Reva

Don't return your view as JSON, just return the view from your controller For example:

不要将您的视图作为 JSON 返回,只需从您的控制器返回视图 例如:

$view = view("<your url>",compact('data'))->render();
return $view;

This will work for sure.

这肯定会起作用。

回答by Chris Hymanson

Ok - I found by trial and error that you don't include the blade template commands in the view file for this to work.

好的 - 我通过反复试验发现您没有在视图文件中包含刀片模板命令以使其正常工作。

I had:

我有:

@section('content')
<table class="table table-striped">
    <tbody>
@foreach ($userjobs as $userjob)
        <tr>
            <td><strong>{{ $userjob->title }}</strong><br />
            {{ $userjob->description }}
            </td>
        </tr>
@endforeach
</table>
@stop

and now its working with:

现在它与:

<table class="table table-striped">
    <tbody>
    <?php foreach ($userjobs as $userjob){?>
        <tr>
            <td><strong><?php echo $userjob->title; ?></strong><br />
            <?php echo $userjob->description; ?>
            </td>
        </tr>
    <?php } ?>
</table>

Altho I searched - I never found documentation stating this.

尽管我进行了搜索 - 我从未找到说明这一点的文档。

回答by Paris Paraskeva

remove this if condition and see if it works

删除这个 if 条件,看看它是否有效

if(Request::isMethod('post') && Request::ajax()) {

回答by Nole

This helped me:

这对我有帮助:

echo view('ajaxView')->with(['value' => 'some value']);

I have used echoview('ajaxView')instead returnview('ajaxView').

我使用echoview('ajaxView')而不是 returnview('ajaxView')

回答by Wahsei

I got it working without these : @section & @stop

我在没有这些的情况下工作:@section & @stop

<table class="table table-striped">
    <tbody>
@foreach ($userjobs as $userjob)
        <tr>
            <td><strong>{{ $userjob->title }}</strong><br />
            {{ $userjob->description }}
            </td>
        </tr>
@endforeach
</table>

either

任何一个

$returnHTML = view('job.userjobs',[' userjobs'=> $userjobs])->render();// or method that you prefere to return data + RENDER is the key here

or this

或这个

$returnHTML = view('job.userjobs',compact($userjobs))->render();// or method that you prefere to return data + RENDER is the key here`

both worked

都工作

回答by mohamed

$view = view("job.userjobs",compact($userjobs))->render();
return response()->json(['html'=>$view]);