laravel 5 和 Ajax 从数据库中获取数据:
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30893777/
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
laravel 5 and Ajax get data from database:
提问by pavlenko
I have simple form:
我有简单的形式:
{{ Form::open(array('id' => 'frm')) }}
<div class="form-group">
{!! Form::label('id','id:'); !!}
{!! Form::text('id',null,['class' => 'form-control']); !!}
</div>
<div class="form-group">
{!! Form::submit('Update',['class' => 'btn btn-primary form-control']); !!}
{!! Form::close() !!}
I want to post the values from the form input fields to the controller then in the controller mthod run a query on the database for the id value from the form. Finally, using ajax, show the results of the DB query and if there are no results show a message alerting the user.
我想将表单输入字段中的值发布到控制器,然后在控制器中运行查询数据库以获取表单中的 id 值。最后,使用 ajax,显示数据库查询的结果,如果没有结果,则显示一条消息提醒用户。
I have tried this:
我试过这个:
<script>
$("document").ready(function(){
$("#frm").submit(function(e){
e.preventDefault();
var customer = $("input[name=postal]").val();
$.ajax({
type: "POST",
url : "http://laravel.test/ajax",
data : dataString,
dataType : "json",
success : function(data){
}
}, "json");
});
});//end of document ready function
</script>
I have tried a couple of ways to get the post
data in the controller but have had no success.
我尝试了几种方法来获取post
控制器中的数据,但都没有成功。
---Problem 1:
---问题1:
There is problem when I try to use this in route:
当我尝试在路由中使用它时出现问题:
Route::post('ajax', function() { // callback instead of controller method
$user = App\User::find(\Input::get('id');
return $user; // Eloquent will automatically cast the data to json
});
I get sintax error,on second line for (;)
我收到语法错误,在 (;) 的第二行
Also, I try to get data in controller and than print them:
另外,我尝试在控制器中获取数据而不是打印它们:
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
ROUTES.PHP
路由文件
Route::post('/',
['as' => 'first_form', 'uses' => 'TestController@find']);
Route::get('/', 'TestController@index');
Route::post('ajax', function() { // callback instead of controller method
$user = App\User::find(\Input::get('id');
return $user; // Eloquent will automatically cast the data to json
});
Function:
功能:
public function ajax()
{
//
// Getting all post data
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
}
I found a couple more ways to send data from view to controller,but even woant show posted data. I check with fire-bug,there is posted value in post request
我找到了几种将数据从视图发送到控制器的方法,但甚至不想显示已发布的数据。我检查了 fire-bug,post 请求中有 post 值
回答by haakym
It appears you're passing your ajax method a variable that doesn't exist. Try passing it the form data directly and see if that yields any results, you can do this with the serialize
method:
看来您正在向 ajax 方法传递一个不存在的变量。尝试直接将表单数据传递给它,看看是否会产生任何结果,您可以使用以下serialize
方法执行此操作:
$("#frm").submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url : "http://laravel.test/ajax",
data : form.serialize(),
dataType : "json",
success : function(data){
if(data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});
The ajax call has console.log
in it now so it will output anything returned to it in the console.
ajax 调用console.log
现在包含在其中,因此它将在控制台中输出返回给它的任何内容。
routes.php(an example)
route.php(一个例子)
Route::post('ajax', function() { // callback instead of controller method
$user = App\User::find(\Input::get('id'));
return $user; // Eloquent will automatically cast the data to json
});
Please bear in mind I am just putting the code as an example as you didn't put your controller code in the question.
请记住,我只是将代码作为示例,因为您没有将控制器代码放在问题中。
EDIT
编辑
I'm going to make a really simple example that works for you. I have made a fresh install of laravel and coded this and it's working fine for me. Please follow along carefully.
我将做一个非常简单的例子,对你有用。我已经重新安装了 laravel 并对其进行了编码,它对我来说很好用。请仔细跟随。
app/Http/routes.php
应用程序/Http/routes.php
<?php
// route for our form
Route::get('/', function() {
return view('form');
});
// route for our ajax post request
Route::post('ajax', function() {
// grab the id
$id = \Input::get('id');
// return it back to the user in json response
return response()->json([
'id' => 'The id is: ' . $id
]);
});
resources/views/form.blade.php
资源/视图/form.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax Example</title>
</head>
<body>
{!! Form::open(['url' => 'ajax', 'id' => 'myform']) !!}
<div class="form-group">
{!! Form::label('id','id:') !!}
{!! Form::text('id', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Update',['class' => 'btn btn-primary form-control']); !!}
</div>
{!! Form::close() !!}
<div id="response"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("document").ready(function(){
// variable with references to form and a div where we'll display the response
$form = $('#myform');
$response = $('#response');
$form.submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url : $form.attr('action'), // get the form action
data : $form.serialize(), // get the form data serialized
dataType : "json",
success : function(data){
$response.html(data['id']); // on success spit out the data into response div
}
}).fail(function(data){
// on an error show us a warning and write errors to console
var errors = data.responseJSON;
alert('an error occured, check the console (f12)');
console.log(errors);
});
});
});
</script>
</body>
</html>