【PHP】异步请求

<!-- ajax -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script>
    $('#answer-btn').on('click', function () {
      $question_id = {{ $question->id }};
      $answer_choice = {{ $question->answer_choice }};
      $answered_choice = Number($('input[name="answer"]:checked').val());
      console.log($answered_choice);
      console.log($answer_choice);
      console.log($question_id);
       $.ajax({
        type: "POST",
        url: "/question/choice",
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
        data: { 'answered_choice': $answered_choice, 'question_id': $question_id },
      });
    })
</script>
<!-- ajax -->
  /**
   * Remove the specified resource from storage.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function choice(Request $request)
  {
      $answered_choice = $request->answered_choice;
      $question_id = $request->question_id;
      $question = Question::find($question_id);
      if($answered_choice == $question->answer_choice){
        $question->update(["status_num" => 2]);
      } else {
        $question->update(["status_num" => 3]);
      }
  }
use App\Http\Controllers\QuestionController;
Route::resource('/question',  QuestionController::class)->middleware('auth');
Route::post('/question/choice',  [QuestionController::class, 'choice'])->middleware('auth');
广告
将在 10 秒后关闭
bannerAds