Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel5.4:提交HTML表单并接收JSON响应_Json_Ajax_Laravel_Controller - Fatal编程技术网

Laravel5.4:提交HTML表单并接收JSON响应

Laravel5.4:提交HTML表单并接收JSON响应,json,ajax,laravel,controller,Json,Ajax,Laravel,Controller,问:如何将JSON从控制器传回html页面,并将响应嵌入页面,而不是破坏页面 长话短说是这样的: $('form').on('submit', function(e){ e.preventDefault(); //1 var $this = $(this); //alias form reference $.ajax({ //2 url: $this.prop('action'), method: $this.prop('method'

问:如何将JSON从控制器传回html页面,并将响应嵌入页面,而不是破坏页面

长话短说是这样的:

$('form').on('submit', function(e){
    e.preventDefault(); //1

    var $this = $(this); //alias form reference

    $.ajax({ //2
        url: $this.prop('action'),
        method: $this.prop('method'),
        dataType: 'json',  //3
        data: $this.serialize() //4
    }).done( function (response) {
        if (response.hasOwnProperty('status')) {
            $('#target-div').html(response.status); //5
        }
    });
});
嵌入在一个相当大的html页面中,当我打开我的基本URL时,视图创建了这个页面,比如说,我有一个html表单。它有一些数据字段和常用的提交按钮

<form class="form-horizontal" method="POST" action="{{ route('form.user') }}">
    {{ csrf_field() }}

    ... lots of input fields ...

    <div class="form-group">
        <button type="submit" class="btn btn-primary">
            Submit
        </button>
    </div>
</form>
控制器

public function save(Request $request) {

...
return response()->json(['status' => 'Saved successfully']);
}

整个过程就像预期的一样,如果我填写表单并点击Submit按钮,控制器将通过$request属性接收所有输入字段

从控制器返回后,html从浏览器中清除,并显示JSON,问题就会出现

我需要的是接收JSON并将其显示在原始html的div中,而不是替换它

问:我需要做什么,如何连接到通信中来截取和处理JSON响应,以便使用JQuery在原始网页中显示响应文本,而不破坏html

谢谢,阿明

捕获表单提交事件,并阻止默认设置。 构造一个AJAX请求 指定响应类型。 将表单数据转换为要发送到服务器的序列化对象 捕获返回的响应并将其应用于DIV。 看起来是这样的:

$('form').on('submit', function(e){
    e.preventDefault(); //1

    var $this = $(this); //alias form reference

    $.ajax({ //2
        url: $this.prop('action'),
        method: $this.prop('method'),
        dataType: 'json',  //3
        data: $this.serialize() //4
    }).done( function (response) {
        if (response.hasOwnProperty('status')) {
            $('#target-div').html(response.status); //5
        }
    });
});

看起来很有希望,非常感谢,我今天会试试,让你知道会发生什么。对不起,同样的问题。显然不会调用success,而是在浏览器中显示返回的JSON。我需要在服务器端的响应中添加一些内容,这样浏览器就不会试图显示它吗?@Nimral,你需要e.preventDefault来确保提交到服务器的表单的默认操作不会发生。preventDefault已经就位,我使用的代码几乎是你给我的示例的100%副本。代码正在工作!我还有几行。为了跟踪问题,我注释掉了几行代码,突然代码开始工作。我还没有发现是哪种奇怪的副作用破坏了它,但无论如何,原因在我这一部分,而不是你。有时这种代码注入的东西会变得有点复杂。谢谢