首页 > 解决方案 > 在 Laravel 中通过 Ajax 获取表单中的数据

问题描述

我正在制作一个自动完成表单,其中用户只输入 id,与该 id 相关的全部信息出现在其他字段中。我正在使用 ajax 和 Laravel 5.4。数据即将发出警报,但我如何在表单的输入字段中插入数据。这是我的脚本:

<script type="text/javascript">
 $('#submitid').on('click', function() {

    var vid = $( "#vid" ).val();
       //var id=$(this).data('id');

        $.ajax({
              url: '/inquiryVendor',
              type: "Get",
              data:{id:$("#vid").val()}, // the value of input having id vid
               success: function(response){ // What to do if we succeed

            alert(response); console.log(response);


        }
            });
    });
</script>

这是我的控制器:

public function VendorDetail(Request $request)
    {

    $id= $request->id;

      $data = DB::select(DB::raw("SELECT * from bp where id = '$id'"));
      echo json_encode($data);

    }

这是我的 console.log 回复:

[{"id":37,"card_name":"Maka Furniture Co.,Ltd ","trade_type":"Manufacturer","address":"Xinzhang development zones,Shengfang town,Hebei province.","fc":"121AC209","status":0,"created_at":"2018-10-10 10:02:27","user":"admin"}]

这是响应的屏幕截图:

在此处输入图像描述

任何帮助都将是非常可观的。

标签: javascriptphpjqueryajaxlaravel

解决方案


如果您想要单个输入中的所有数据,您可以使用它

<script type="text/javascript">
     $('#submitid').on('click', function() {

        var vid = $( "#vid" ).val();
           //var id=$(this).data('id');

            $.ajax({
                  url: '/inquiryVendor',
                  type: "Get",
                  dataType: 'json',//this will expect a json response
                  data:{id:$("#vid").val()}, 
                   success: function(response){ 
                        $("#inputfieldid").val(response);     
            }
                });
        });
    </script>

或者如果你想在不同的输入字段上你可以这样做

<script type="text/javascript">
 $('#submitid').on('click', function() {

    var vid = $( "#vid" ).val();
       //var id=$(this).data('id');

        $.ajax({
              url: '/inquiryVendor',
              type: "Get",
              dataType: 'json',//this will expect a json response
              data:{id:$("#vid").val()}, 
               success: function(response){ 
                    $("#inputfieldid1").val(response.id); 
                    $("#inputfieldid2").val(response.2ndcolumnName);
                    $("#inputfieldid").val(response.3rdcolumnName); 

        }
            });
    });
</script>

推荐阅读