如何拨打路线&用javascript发送数据

时间:2018-04-21 23:34:47

标签: javascript php jquery laravel laravel-5

我正在使用Laravel 5并且我使用了以下代码

HTML

<div id="row">
  <textarea class="form-control" rows="3" id="comment" placeholder="Update your Post"></textarea>
</div>

<a href="#" id="btn-post" dusk="postButton" class="btn btn-primary" role="button" data-toggle="modal" data-target="#addPost">
  <span class="ion-plus-circled"> Post</span>
</a>

JS

$(document).ready(function(){

$("#btn-post").click(function(){
    $.ajaxSetup({
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    var comment = $('textarea#comment').val();
    var postData = {
        post_content: comment.val();
        groupId: window.location.href.split("/")[4] // hack to get group id
    }

    console.log(postData);

    $.ajax({
        type: "POST",
        url: "/post",
        data: JSON.stringify(postData),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data, status){
        $("#addPost").modal('toggle');
            //window.location.href = data.redirectTo;                  
        }
    });
  });
});

web.php

Route::post('post', 'GroupController@post');

GroupController.php

public function post(Request $request){
    $post_content = $request->input('post_content');
    $userId = Auth::user()->id;
    $groupId = $request->input('groupId');

    $post = PostGroup::firstOrNew(['group_id' => $groupId, 'post_content' => $post_content]);
    $post->user_id = $userId;

    $post->save();

    $redirectPath = '/groups/' . $groupId;
    return response()->json(['message' => 'Your post have been published! Take a look at',
        'redirectTo' => $redirectPath]);
}

我想要做的是点击链接按钮btn-post调用javascript函数Post。此函数采用textarea的内容(我不知道我是否正确写入)并使用相同的javascript函数将其发送到GroupController到路由&#34; /发布&#34;,调用函数post(如web.php中所定义),但由于某种原因它不起作用,我不知道我错在哪里(我认为问题出在javascript函数中,就像它没有被调用一样。)

1 个答案:

答案 0 :(得分:2)

您的Javascript中有语法和逻辑错误:

var comment = $('textarea#comment').val();
var postData = {
    post_content: comment.val(); 
    groupId: window.location.href.split("/")[4] // hack to get group id
}

逻辑错误:您将textarea值分配给var comment。然后在那之后2行,你在它上面调用comment.val(),虽然它在这一点上是一个字符串。无需再次致电.val()

语法错误:您不应在; JSON定义中使用postData。您使用逗号分隔JSON字段。

这是针对上述两个问题的解决方法:

var postData = {
    post_content: comment, // <----
    groupId: window.location.href.split("/")[4] // hack to get group id
}

我建议您开始使用开发人员工具来调试您的Javascript