duanpi7578 2019-05-10 20:59
浏览 55

ajax调用仅显示每个循环中第一个项目的输入值。 需要根据按钮点击的上下文显示它

I am trying trying to post data to a controller based on the context of the button click in the for each loop. The response is only showing the first iteration of the loop.


@foreach($obj['questions'] as $question)
        <form class="col-md-12" id="upvote">
        <input type="hidden" value="{{$question->id}}" id="question_id" data-id="{{$question->id}}" class="form-control question_id">
        <input type="hidden" value="{{$user->id}}" id="user_id" data-id="{{$user->id}}" class="form-control user_id">
        <button class="btn btn-xs fas fa-arrow-up btn-submit" style="{{ in_array($question->id, $upvotes) ? 'color:gray' : 'color:orange' }}" {{ in_array($question->id, $upvotes) ? 'disabled' : null }}></button>
        </form>
@endforeach

And my ajax script looks like this:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajaxSetup({
            headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $('.btn-submit').click(function(e){
        e.preventDefault(); 
        var question_id = $("input[id=question_id]").val();
        var user_id = $("input[id=user_id]").val();
            $.ajax({
                url: "{{ route('welcome.upvoteAjax') }}",
                type: 'POST',
                data: {question_id:question_id, user_id:user_id},
                dataType: 'json',
                success: function (data) {
                    console.log(data);
                }
            });
        });
    });
</script>

My route:


Route::post('/upvoteAjax', 'WelcomeController@upvoteAjax')->name('welcome.upvoteAjax');

And my controller looks like this:

public function upvoteAjax(Request $request){
   if($request->ajax()) {
      return response()->json($request);
   }
}

The response I get in console is (I attached a screenshot of the browser as well):

(index):593 {question_id: "736", user_id: "1"}
(index):593 {question_id: "736", user_id: "1"}
(index):593 {question_id: "736", user_id: "1"}

This is the output regardless of which item in the loop I click. The output that I want is the question and the user associated with the iteration of the loop that is displayed on the front end. Any feedback would be appreciated.

Thanks.

This is a screenshot of the console in chrome

  • 写回答

2条回答 默认 最新

  • dongrou839975 2019-05-10 21:11
    关注

    When you are clicking the submit button, You're fetching the value from the first field it finds example

    <input id="question_id">.

    A better way to solve this issue would calling the closeset elements input types to get the value:

        var question_id = $(this).closest('.question_id').val();
    

    This will make sure the form values corresponds the input that button is submitting. Also ID is unique for each element.

    here try this:

    let btns = document.querySelectorAll('.btn')
    btns.forEach((btn) => {
        btn.addEventListener('click', function(event){
            event.preventDefault();
            let question_id =  btn.parentNode.children[0].value
            let user_id = btn.parentNode.children[1].value
    
            $.ajax({
                    url: "{{ route('welcome.upvoteAjax') }}",
                    type: 'POST',
                    data: {question_id: question_id, user_id: user_id},
                    dataType: 'json',
                    success: function (data) {
                        console.log(data);
                    }
            })
    
        })
      })
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!