laravel 通过laravel中的ajax返回视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19692177/
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
Return a view via ajax in laravel
提问by Pars
I want to display a view to the user whenever user clicks on a button using ajax.
This is my code.
我想在用户使用 ajax 单击按钮时向用户显示视图。
这是我的代码。
// BASE = localhost/project/public/
$('#button').click(function() {
$.ajax({
url: BASE + "user/settings",
type: 'GET'
})
.done(function( data ) {
console.log( data );
});
});
And my routes.php
还有我的routes.php
Route::get('user/settings', 'UserController@getSettings');
And UserController.php
和 UserController.php
public function getSettings(){
return View::make('user.settings');
}
But output is this error:
但输出是这个错误:
{"error":{"type":"ErrorException","message":"Undefined offset: 0","file":"H:\dev \xampp\htdocs\lchat\vendor\laravel\framework\src\Illuminate\Support \Collection.php","line":470}}
EDIT: error was in view. I fixed it.
编辑:错误在视野中。我修好了它。
Problem2: The page which is loading via ajax, itself contains another ajax post request. but it's not sending data via ajax anymore. refreshes the page to send data.
问题 2:通过 ajax 加载的页面本身包含另一个 ajax post 请求。但它不再通过ajax发送数据。刷新页面以发送数据。
The jquery code:
jQuery代码:
$('#settings :submit').click(function(e){
e.preventDefault();
$.post(BASE + 'settings/save', {
'userName' : $('#userName').val()
}, function(data) {
return 'OK';
});
});
Problem solved: I used .on
to bind event:
问题解决:我曾经.on
绑定事件:
$(document).on('click', '#settings :submit', function(e){ ... } );
It's working... Thank everyone.
它的工作......谢谢大家。
采纳答案by Shauna
Well, for starters, you have an error in your view. The error you're getting is in reference to an array you're trying to access that doesn't actually have the key you're trying to use ($arr[0]
).
好吧,对于初学者来说,您的观点有误。您收到的错误是对您尝试访问的数组的引用,该数组实际上没有您尝试使用的密钥 ( $arr[0]
)。
Once you fix the errors with the view itself, it should work fine. The JavaScript will get the data as HTML, and you can just insert it into wherever you want it to show up.
使用视图本身修复错误后,它应该可以正常工作。JavaScript 会以 HTML 格式获取数据,您可以将其插入到您想要显示的任何位置。
回答by Imtiaz Pabel
Use string method before view file
在查看文件之前使用字符串方法
return (String) view('Company.allUserAjax');