欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

laravel 怎么使用ajax

shiping1 的头像
laravel5刚好弄了一个,供参考。

1.建议新手至少先弄通golaravel上入门的文章(一)和(二),否则理解比较困难

1
<meta name="_token" content="{{ csrf_token() }}"/>

2.前端js请求部分(注意那个header属性,是为了避免跨站伪造请求攻击写的)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$.ajax({
type: 'POST',
url: '/ajax/create',
data: { date '2015-03-12'},
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
success: function(data){
console.log(data.status);
},
error: function(xhr, type){
alert('Ajax error!')
}
});

3.路由部分route.php(ajax/create路由打到Controllers/Ajax/PollController.php的store方法上处理)

1
2
3
Route::group(['prefix' => 'ajax''namespace' => 'Ajax'], function(){
Route::post('create''PollController@store');
});

控制器方法PollController.php,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php namespace App\Http\Controllers\Ajax;
 
use App\Http\Requests;
use App\Http\Controllers\Controller;
 
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Poll;  // 用数据模型
 
use Redirect, Input, Auth, Log;
 
class PollController extends Controller {
public function store(Request $request)
{
    $poll new Poll;
 
    $poll->date = Input::get('date');
 
    if ($poll->save()) {
        return response()->json(array(
            'status' => 1
            'msg' => 'ok',
        ));
    else {
        return Redirect::back()->withInput()->withErrors('保存失败!');
    }
}
}
来自 http://zhidao.baidu.com/link?url=vm_Aygd2FHYeWf5cUqzZKOkF9GKj1i8MzLJaE8PFpYNF6bGFiduIN2WDJKk51aqIge3...



Laravel 5 can't use ajax post request

jekingohel
jekingohel — 1 year ago

Hello,

I am using laravel 5 for my project. $.ajax request can't use POST request.

I am also passing csrf_token with request. But everytime it throwing error 405 (Method Not Allowed).

Please help me to resolve it.

Thank you.

graham
graham — 1 year ago

@jekingohel do you want to share some code with us?

jekingohel
jekingohel — 1 year ago
<meta name="csrf-token" content="{{ csrf_token() }}" />

var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

$.ajax({
    url: '/home/upload/',
    type: 'POST',
    data: {_token: CSRF_TOKEN},
    dataType: 'JSON',
    success: function (data) {
        console.log(data);
    }
});

Here is code.

sitesense
sitesense — 1 year ago

@jekingohel do you have a 'post' route set up for that?

Route::post('upload','uploadController@yourmethod');
jekingohel
jekingohel — 1 year ago

Yes. I have set up.

Route::post('home/upload', 'HomeController@upload');
bestmomo
 bestmomo — 1 year ago

Are you sure you generate the good url with :

url: '/home/upload/',
sitesense
sitesense — 1 year ago

@jekingohel

Route::post('home', 'HomeController@upload');

And change the path in your ajax call from home/upload to home;

jekingohel
jekingohel — 1 year ago

@sitesense

Have two method in HomeController.php

Route::get('home', 'HomeController@index');
Route::post('home/upload', 'HomeController@upload');
bashy
 bashy — 1 year ago

Easiest way to debug - use a API client like postman or use the browser "network" tab to see the method and path being used. You'll spot your mistake soon enough.

tkjaergaard
 tkjaergaard — 1 year ago

Have you tried to monitor the HTTP request through dev-tools, and verified that the data is sent through correctly?

You could also try out something like postman.

bashy
 bashy — 1 year ago

@tkjaergaard Omg like 5 seconds before you with the exact same info :D snap sir!

jekingohel
jekingohel — 1 year ago

@bestmomo Yes I am generating good url.

sitesense
sitesense — 1 year ago

@jekingohel did you try it - Route::post('home', 'HomeController@upload');?

It doesn't matter whether you have two methods. If a "POST" request hit's the home controller, it will direct to the upload method.

But as @bashy says, any problems with Ajax, you should be using tools to check that you're actually getting a response to the post.

It seems to be surely a path problem.

jekingohel
jekingohel — 1 year ago

@sitesense Your solution works! Thanks.

But have question. If I want to use two method from same controller in $,ajax call then?

Route::post('home/upload', 'HomeController@upload');
Route::post('home/insert', 'HomeController@insert');

it will not work correct. evertytime it will call last method.

Route::post('home', 'HomeController@upload');
Route::post('home', 'HomeController@insert');
sitesense
sitesense — 1 year ago

What you have suggested should be fine:

Route::post('home/upload', 'HomeController@upload');
Route::post('home/insert', 'HomeController@insert');

But you'll need to figure out what's wrong with your route or controller.

The method that I suggested was just to overcome your immediate problem. I could see it was a path issue and it was the easiest way to show you that.

jekingohel
jekingohel — 1 year ago

@sitesense I am using two ajax post method in HomeController. Both method have same problem. $.ajax or $.post request uses GET method. I want to resolve it very soon.

Thanks.

来自 https://laracasts.com/discuss/channels/requests/laravel-5-cant-use-ajax-post-request?page=1


Post data using ajax in laravel 5

 Rakesh Sharma       19 Comments   

Post data using ajax in laravel 5 to controller

If you are going to work with ajax data post to controller or route in laravel 5. There are some need to get ajax call work correctly. Your requirement is csrf token. A default feature in Laravel is it’s automatic CSRF security. When you working with forms it’s automatically add a “_token” hidden field to your form. On each post request token will be matched for csrf protection. so it’s one more cool feature provided by laravel 5.

Why on ajax post 500 internal server error laravel :-

If you are using default way for ajax data post, you will get “500 internal server error” in laravel 5. cause you missing csrf token posting with ajax post data. and error reason is token not being matched on post request. so every time a form data is posting require csrf token match. else you will get “500 internal server error” in laravel.

Post data using ajax in laravel 5

In this article we will explore how to solve 500 internal server error in ajax post or call in laravel or how to Post data using ajax in laravel 5. there are many ways to do this but i am sharing two ways :-

1. Adding on each request
2. globally

How to Post data using ajax in laravel 5 :-

1. Adding on each request and post data to controller :-

In this way we need to add token on each ajax call with data which is posting

view :- add a “login.blade.php” under “resources/views/” and add below code to make a form


<div class="secure">Secure Login form</div>
{!! Form::open(array('url'=>'account/login','method'=>'POST', 'id'=>'myform')) !!}
<div class="control-group">
  <div class="controls">
     {!! Form::text('email','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Email')) !!}
  </div>
</div>
<div class="control-group">
  <div class="controls">
  {!! Form::password('password',array('class'=>'form-control span6', 'placeholder' => 'Please Enter your Password')) !!}
  </div>
</div>
{!! Form::button('Login', array('class'=>'send-btn')) !!}
{!! Form::close() !!}

Now add your ajax call or post data script to your layout footer or in the same file.


<script type="text/javascript">
$(document).ready(function(){
  $('.send-btn').click(function(){            
    $.ajax({
      url: 'login',
      type: "post",
      data: {'email':$('input[name=email]').val(), '_token': $('input[name=_token]').val()},
      success: function(data){
        alert(data);
      }
    });      
  }); 
});
</script>

Routes :- Add your get and post route to “app/Http/routes.php”


Route::get('account/login', function() {
  return View::make('login');
});
Route::post('account/login', 'AccountController@login');

Controller :- add a controller to “app/Http/Controllers” with named “AccountController.php” and add below code


<?php namespace App\Http\Controllers;
use Input;
use Request;
class AccountController extends Controller {
  public function login() {
    // Getting all post data
    if(Request::ajax()) {
      $data = Input::all();
      print_r($data);die;
    }
}

After all make go to your page url and click on button and you get your data has been posted and you will get alert with success.

2. globally way :-

In this way we will add token for globally work with ajax call or post. so no need to send it with data post.

1. Add a meta tag to your layout header :- csrf_token() will be the same as "_token" CSRF token that Laravel automatically adds in the hidden input on every form.


<meta name="_token" content="{!! csrf_token() !!}"/>

2. Now add below code to footer of your layout, or where it will set for globally or whole site pages. this will pass token to each ajax request.


<script type="text/javascript">
$.ajaxSetup({
   headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>

Now make an ajax post request an you are done your data will post successfully.

来自 https://laracasts.com/discuss/channels/requests/laravel-5-cant-use-ajax-post-request?page=1
普通分类: