【问题标题】:Laravel JQuery AJAX POST get dataLaravel JQuery AJAX POST 获取数据
【发布时间】:2017-07-30 11:16:38
【问题描述】:

我有一个代码:

var bet = {
    tournament: '',
    bo: '1',
    bet_team: '2',
    betted: '3',
    potential: '4',
    percent: '5'
};

$.ajax({
    type: 'POST',
    url: '/api/makeBet/',
    data: bet,
    contentType: 'application/json',
    dataType: 'json',
    success: function(data) {
        if(data.error) {
            sweetAlert("Oops...", data.data, "error");
        } else {
            sweetAlert("Success!", data.data, "success");
        }
    },
    error: function(html, status) {
        console.log(html.responseText);
        console.log(status);
    }
});

但是当我尝试获取 $request->tournament 或其他内容时,我什么也得不到。

【问题讨论】:

  • 控制器/路由的代码在哪里?
  • 你能在你尝试使用$request的地方展示Route和控制器方法吗?
  • Route::post('/api/makeBet', 'APIController@makeBet')->name('makeBet');公共函数 makeBet(请求 $request)
  • 尝试添加完整的网址,例如url: 'localhost:8000/api/mekeBet'
  • 如果你想在成功函数中看到一些数据,你需要返回一些东西,例如在你的makeBet方法return $request->all()

标签: php ajax laravel laravel-5


【解决方案1】:

这对我有用

function filter_by_department()
{
    var bet = {
    tournament: '',
    bo: '1',
    bet_team: '2',
    betted: '3',
    potential: '4',
    percent: '5'
};
var token;
token='{{ csrf_token() }}';
console.log(token);
$.ajax({
   headers: {
      'X-CSRF-TOKEN': token
},
    type: 'POST',
    url: 'task_department',
    data: bet,
    dataType: 'html',
    success: function(data) {
        if(data.error) {
            sweetAlert("Oops...", data.data, "error");
        } else {
            console.log(data);

        }
    },
    error: function(html, status) {
        console.log(html.responseText);
        console.log(status);
    }
});
}

【讨论】:

    【解决方案2】:

    您的错误有很多可能的原因。

    • 您的路线
    • 你的控制器
    • 你的锦标赛是空的

    发布您的代码可以大有帮助;同时,这可能会有所帮助:

    路线...

    Route::post('/api/makeBet/', 'YourController@index');
    

    控制器...

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    
    class YourController extends Controller
    {
        //
        public function index(Request $request)
        {
            $tournament = $request->tournament //gives tournament
        }
    }
    

    【讨论】:

      【解决方案3】:

      您需要使用JSON.stringify 首先将您的对象序列化为 JSON,然后指定内容类型,以便您的服务器理解它是 JSON。这应该可以解决问题:

      var bet = {
          tournament: '',
          bo: '1',
          bet_team: '2',
          betted: '3',
          potential: '4',
          percent: '5'
      };
      
      $.ajax({
          url: '/api/makeBet/',
          method: 'post',
          contentType: 'application/json',
          data: JSON.stringify(bet),
          success: function(data) {
                 // so something        
          }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-15
        • 1970-01-01
        • 1970-01-01
        • 2017-12-25
        • 1970-01-01
        • 2019-11-05
        • 1970-01-01
        相关资源
        最近更新 更多