亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel - 檢查數據是否存在于javascript中的數據庫中

Laravel - 檢查數據是否存在于javascript中的數據庫中

翻閱古今 2022-11-11 16:21:50
我正在用 Laravel 7 構建一個表單。首先,用戶需要在 datalist 輸入框中選擇一項,一旦選擇就會顯示相應的詳細信息(“模糊”輸入框)。用戶還可以將自定義項目添加到列表中。數據庫用于存儲所有項目,如果用戶添加自定義項目,它將存儲在數據庫中以便顯示。因此,由于它是一個輸入框,因此用戶可以輸入。如果數據庫中不存在輸入,我希望它不顯示任何信息,直到用戶點擊添加按鈕將自定義項目添加到數據庫以及輸入下拉列表中,然后將顯示默認信息。但是如何判斷輸入是否存在于數據庫中呢?表單是這樣的,我使用 Jquery 來隱藏/顯示div選擇了哪個項目。<form action"/send" method="post">  <div id="info1">    <!-- info about first item -->      </div>  <div id="info2">    <!-- info about second item -->  </div>  <div id="info_default">    <!-- if customised item is chosen, show this one -->    </div>  <div id="info_does_not_exist">    <!-- if cannot find the input item in database, show this one -->    </div>  <button type="submit">submit</button></form>
查看完整描述

2 回答

?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

對于簡單的方法,我推薦你使用 jQuery 的 Ajax,這樣你不需要做太多的改變,為 API 添加一個路由,檢查數據庫中的數據和幾行 JavaScript 代碼。您可以嘗試以下方法:


控制器:


use Your\Namespace\Path\Of\Model Model

Class ABC {

    ...

    public function checkExist(){

        $data = request()->get('data'); // get data to check

        $model = new Model();

        $where = ['id' => $data]; // passing your where condition to check

        return $model->where($where)->get()->count() > 0;

    }

}

路由文件(web.php/api.php):


路線::get('checkExist', 'ABC@checkExist');


看法


<form action"/send" method="post">

  <div id="info1">

    <!-- info about first item -->    

  </div>


  <div id="info2">

    <!-- info about second item -->

  </div>


  <div id="info_default">

    <!-- if customised item is chosen, show this one -->  

  </div>


  <div id="info_does_not_exist">

    <!-- if cannot find the input item in database, show this one -->  

  </div>


  <button type="submit">submit</button>

</form>

...

<script>

  $(function(){

    // every time input change, check value existence in database

    $('.info2 input').change(function(){

      let input_value = $(this).val();

      $.ajax({

        url: "{{ route('checkExist') }}",

        method: "GET",

        data: {"id": input_value},

        success: function(response){

          // process if/else to show div '.info_default' / '.info_does_not_exist'

          if (response) {

            // show '.info_default' and hide '.info_does_not_exist'

          } else {

            // show '.info_does_not_exist' and hide '.info_default'

          }

        }

      });

    })

  })

</script>

這不是實際的可運行代碼,只是一個想法,根據這個,您可以根據您的進一步需求對其進行調整。希望這會有所幫助


查看完整回答
反對 回復 2022-11-11
?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

您必須使用 AJAX 之類的東西來檢查數據庫中的用戶輸入值,然后做出正確的決定,在添加或顯示數據庫中的內容之前不顯示任何內容。

因此工作流程如下:用戶輸入 => ajax 接受用戶輸入并提交給控制器函數以檢查數據庫是否存在值 => 取決于從該控制器函數返回的值 => 向用戶顯示正確的值


查看完整回答
反對 回復 2022-11-11
  • 2 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號