weixin_33725239 2016-02-28 03:36 采纳率: 0%
浏览 16

如何使用laravel5 Ajax发布

I can't through the $request->ajax(), I can get and dd($data), but it always return false, what's wrong with my code.could anyone help me? thanks.

route

Route::post('test', 'BlogController@test');

view

<form method="POST" id="form-ajax" action="/test">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <div class="form-group">
        <label for="name1">Name1</label>
        <input type="text" class="form-control" name="name1" id="name1">
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary" id="test_btn">
            Submit
        </button>
    </div>
</form>

controller

public function test(Request $request)
{
    $data = $request->input('name1');
    if ($request->ajax()) {
        $response = array(
            'name' => $data,
            'status' => 'success',
        );
        return response()->json($response);
    } else
        return response()->json(['msg' => 'false']);
}

js

$(document).ready(function() {
            $('#test_btn').click(function() {
                $.ajax({
                    url: '/test',
                    type: 'post',
                    data: {'_token': $('input[name=_token]').val(), 'name1': $('input[name=name1]').val()},
                    success: function(data) {
                        console.log(data);
                    },
                    headers: {'X-Requested-With': 'XMLHttpRequest'},
                    dataType: 'json'
                });
            });
        });
  • 写回答

1条回答 默认 最新

  • weixin_33717117 2016-02-28 04:15
    关注

    If you dig in the code, you will find out that $request->ajax() method relies on this logic (see vendor/symfony/http-foundation/Request.php):

    $this->headers->get('X-Requested-With');
    

    jQuery does set this header by default. First action you should do – see how your AJAX call looks in the Developer Tools in your browser. You can see full HTTP headers there – do the headers contain this X-Requested-With line?

    If it's not there (unlikely but who knows), you could manually add it to your AJAX data object, eg: "X-Requested-With":"XMLHttpRequest".

    Also, I would advise to replace $data = $request->get('name1'); with

    $data = $request->input('name1');
    

    Which is more correct way to get an input variable (get() method doesn't even exist in the documentation).

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体