【问题标题】:How to send data from view to controller laravel with ajax?如何使用ajax将数据从视图发送到控制器laravel?
【发布时间】:2021-03-25 00:13:24
【问题描述】:

我无法将数据从视图发送到控制器 laravel 版本 7 我从表单和 ul li 发送数据 我在 javascript 中有数组数据

我的 html 代码是:

我无法将数据从视图发送到控制器 laravel 版本 7 我从表单和 ul li 发送数据 我在 javascript 中有数组数据

<ul name="ali" id="singleFieldTags" class="tagit ui-widget ui-widget-content ui-corner-all">
    <li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
        <span class="tagit-label">reza</span>
        <a class="tagit-close">
            <span class="text-icon">×</span>
            <span class="ui-icon ui-icon-close"></span>
        </a>
    </li>
    <li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
        <span class="tagit-label">ali</span>
        <a class="tagit-close">
            <span class="text-icon">×</span>
            <span class="ui-icon ui-icon-close"></span>
        </a>
    </li>
    <li class="tagit-new">
        <input type="text" class="ui-widget-content ui-autocomplete-input" autocomplete="off">
    </li>
</ul>


     <form id="form" method="post"  action="/save_new" enctype="multipart/form-data">
        @csrf

        <div class="form-group">
            <label for="title">title</label>
            <input type="text"  name="title"  class="form-control">
        </div>

        <div class="form-group">
            <label for="choose-file" class="custom-file-upload" id="choose-file-label">
                Click Here to upload image

            </label>
            <br/>
            <br/>
            <label >no image selected !</label>
            <input name="uploadDocument" type="file" id="choose-file"
                   accept=".jpg,.jpeg,.pdf,doc,docx,application/msword,.png" style="display: none;" />
        </div>

        <div class="form-group">
            <label for="title">Description</label>
            <textarea  name="meta_description"  class="form-control"></textarea>
        </div>

        <div class="form-group">
            <label >keywords</label>
            <input name="tags" id="mySingleField" value="reza,ali" type="hidden" disabled="true">
            <ul name="ali" id="singleFieldTags"></ul>
        </div>

        <button  type="submit"  onclick="myF()" class="btn btn-success pull-left"> save</button>



    </form>

在我的 javascript 中

 <Script type="text/javascript">
  function myF() {
        var data2 = [];
        var inputs = $(".tagit-choice");

        for (var i = 0; i < inputs.length; i++) {
            data2[i] = $(inputs[i]).text();
        }

           $.ajax({
            url:'/save_new',
            type: 'POST',
            dataType:'json',
            // data: JSON.stringify(data2),
            data: JSON.stringify(data2),
            contentType: 'application/json; charset=utf-8',
                    success: function( data ){
                        console.log('ok');
                        console.log(data);
                    },
                    error: function (xhr, b, c) {
                        console.log('error');
                        console.log("xhr=" + xhr + " b=" + b + " c=" + c);
                    }
        });
    }

当我从 ajax 发送数据时,控制台出现错误

error reza:263:37
xhr=[object Object] b=error c=

但在请求 JSON 中 我明白了

0   "reza×"
1   "ali×"

请帮帮我谢谢

我的控制器是:

    public function save_new(Request $request){
//        dd($request->all());

dd($request->getContent());

}

我的路线是:

Route::POST('/save_new','Backend\AdminPostController@save_new')->name('save_new');

编辑:

我的问题比你们都解决了

            var fd = new FormData();
        var file = $("#form input[name=uploadDocument]")[0].files;
        fd.append('file', file[0]);
        fd.append('title', $("#form input[name=title]").val());
        fd.append('description', $("#form textarea[name=meta_description]").val());
        fd.append('tags', JSON.stringify(data2));

        $.ajax({
            type: 'post',
            url: '/ok2',
            contentType: false,
            processData: false,
            data: fd,
            success: function(response) {
                
            },
            error: function  (response) {},
        });

【问题讨论】:

  • 在您的浏览器开发者工具中,切换到网络选项卡并发布您在发送此请求时从后端收到的错误。
  • 我认为后端发生了错误。你应该再检查一次。如果可能的话,你能分享你的控制器吗?

标签: javascript arrays ajax laravel


【解决方案1】:

我不确定你的工作,但这是通过 jquery 发送数据的基本方法之一,请确保将 ajaxSetup 放入 document.ready 函数中

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

$('#form').on('submit',function(){
    $.ajax({
    type:'post',
    url:$("#form").attr('action'),
    data:$("#form").serializeArray(),
    success:function(data){
        //response
        console.log(data);
      }
  });
});

【讨论】:

  • 我正在尝试您的代码,但我再次在控制台中收到错误!当然,我在成功错误后添加此代码: function (xhr, b, c) { console.log('error'); console.log("xhr=" + xhr + " b=" + b + " c=" + c); }
  • 如果成功,您可以尝试使用 get 类型,问题与 csrf 令牌有关,那么我可以为您提供代码
  • 我已经编辑了我的代码,将 ajax 设置放在 document.ready 函数中并尝试
  • 我在我的代码中设置了 ajax 设置但我有错误:(我不知道我的问题是什么
  • 我在查看源代码中看到此错误400 Bad Request

    Bad Request

    您的浏览器发送了此服务器无法理解的请求。

猜你喜欢
  • 2016-03-21
  • 2014-12-06
  • 2019-11-13
  • 2021-04-07
  • 2018-05-20
  • 2017-03-11
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多