@extends('layouts.app')
@section('content')
{{--<p>{{$news}}</p>--}}
<p class="container">
<p class="col-lg-2"></p>
<p class="col-lg-8" id="test">
<p class="form">
<input type="text" name="title" id="title" class="form-control">
<textarea name="tcontent" id="tcontent" cols="30" rows="10" class="form-control"></textarea>
<button id="submit" class="btn-primary">提交</button>
</p>
<p id="test1"></p>
</p>
</p>
<script type="text/javascript">
$(document).ready(function (){
$('submit').click(function (){
var data = {
title: $('#title').val(),
tcontent: $('#tcontent').val()
};
$.ajax({
type: "post",
url: 'news/news',
data: data,
dataType: 'json',
headers: {
'X-CSRF-TOKEN': '{{csrf_token()}}'
},
success: function(data){
console.log(data);
var test1 = '<h1> add success</h1>';
console.log(test1);
$('#test').append(test1);
},
error: function (data){
console.log(data);
var test1 = '<h1>add faild</h1>';
console.log(test1);
$('#test').append(test1);
}
});
});
});
</script>
@endsection
public function store(Request $request)
{
$user = Auth::user();
$this->validate($request,[
'title'=>'required',
'tcontent'=>'required'
]);
$news = new News();
$news->title = $request->get('title');
$news->content = $request->get('tcontent');
$news->author = $user->name;
$news->save();
return $news;
}
Auth::routes();
Route::get('/','HomeController@index')->name('home.page');
Route::group(['prefix'=>'back'], function (){
Route::resource('/news/news','News\NewsController');
Route::group(['prefix'=>'commodity', 'namespace'=>'commodity'], function (){
Route::resource('/classify','ClassifyController');
Route::resource('/commodity','CommodityController');
});
});
The code is as above, nothing happens when clicking the submit button, and no records are inserted into the database. jQuery has also been introduced in the header of the parent page. The page code, controller, and routing settings are as above. I really don’t know what went wrong. Please give the answers
The problem has been solved
1.$('submit') is missing a # number and cannot be retrieved. It should be $('#submit')
2.url should be /back/news/news
The URL is wrong.
In addition, open the console.log and take a look at the error report and it will be resolved.
It should be that js did not obtain the clicked or submitted object. When encountering ajax problems, you generally need to look at the console and network to analyze whether there are network requests, as well as the request and response information.