欢迎各位兄弟 发布技术文章
这里的技术是共享的
PUBLISHED 1 YEAR AGO BY UFODISKO
Anyone has a clear example on how to implement GET and POST requests using Ajax in jQuery?
Not only the jQuery code but also routes and controllers, please.
I'm just trying to see if I can implement it on the blog from "Laravel 5 Fundamentals"
@ufodisko Your routes.php
get('/test', 'SomeController@testfunction');
post('/test', 'SomeController@testfunction');
Your SomeController.php
...
class SomeController extends Controller
{
public function testfunction(Illuminate\Http\Request $request)
{
if ($request->isMethod('post')){
return response()->json(['response' => 'This is post method']);
}
return response()->json(['response' => 'This is get method']);
}
}
your ajax.js
...
$.get('/test', function(){
console.log('response');
});
...
What about Response::json()?
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return Response::json($response); // <<<<<<<<< see this line
}else{
return 'no';
}
Do I include this to my controller?
@ufodisko updated, i pressed publish button.
I am not using $request->isMethod
- would that be a problem?
Anyway, I'm gonna try it out now.
EDIT: it worked, thank you. It even worked with Eloquent which is fantastic. But there is a snag. At the moment, it's displaying a json result whenever I submit new article. How can I have it redirect to a new page and then flash a message or stay on the same page and show them the success/failure message?
public function store(Requests\ArticleRequest $request)
{
$article = new Article($request->all());
Auth::user()->articles()->save($article);
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
$(document).ready(function() {
$('#submit').on('submit', function (e) {
e.preventDefault();
var title = $('#title').val();
var body = $('#body').val();
var published_at = $('#published_at').val();
$.ajax({
type: "POST",
url: host + '/articles/create',
data: {title: title, body: body, published_at: published_at},
success: function( msg ) {
$("#ajaxResponse").append("<div>"+msg+"</div>");
}
});
});
});
If I comment out return Response
I get a blank page on submit.
In your ajax.
success: function( data ) {
$("#ajaxResponse").append("<div>"+data.msg+"</div>");
}
or
success: function( data ) {
$('#ajaxResponse').empty();
$("#ajaxResponse").html("<div>"+data.msg+"</div>");
}
I keep getting the json response
{
"status": "success",
"msg": "Setting created successfully"
}
I'm also returning Response::json()
in my Controller, could that have anything to do with it?
来自 https://laracasts.com/discuss/channels/general-discussion/laravel-5-ajax-get-and-post-examples