简体   繁体   English

在 Laravel 5 中使用 Ajax 并返回 json 数组

[英]Using Ajax and returning json array in laravel 5

在此处输入图片说明I am new to "AJAX" and I have been trying to send a request "ONSELECT" using "AJAX" and receive a "JSON" response in "laravel 5".我是“AJAX”的新手,我一直在尝试使用“AJAX”发送请求“ONSELECT”并在“laravel 5”中接收“JSON”响应。

Here is my View这是我的观点

<select>
<option data-id="a" value="a">a</option>
<option data-id="b" value="b">b</option>
<option data-id="c" value="c">c</option>
</select>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<script type="text/javascript">
$('select').change(function(){
var data = $(this).children('option:selected').data('id');

$.ajax({
    type    :"POST",
    url     :"http://localhost/laravel/public/form-data",
    dataType:"html",
    data    :{ data1:data },

    success :function(response)
    alert("thank u");
    }),
});
</script>

Here is my Controller to receive ajax request这是我接收ajax请求的控制器

public function formdata(){
    $data = Input::get('data1');

    //somecodes

    return Response::json(array(
                    'success' => true,
                    'data'   => $data
                )); 
}

Here is my Route这是我的路线

 Route::post('form-data',array('as'=>'form-data','uses'=>'FormController@formdata'));

I also have tried to change the URL of ajax with just only form-data and {{Url::route('form-data')}} .我还尝试仅使用form-data{{Url::route('form-data')}}更改 ajax 的 URL。

Laravel 5 uses csrf token validation for security reasons....try this... Laravel 5 出于安全原因使用 csrf 令牌验证......试试这个......

  1. In routes.php在routes.php

     route post('form-data', 'FormController@postform');
  2. In master layout file在主布局文件中

    <meta name="csrf-token" content="{{ csrf_token() }}" />
  3.  var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content'); var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
     $.ajax({ url: '/form-data/', type: 'POST', data: {_token: CSRF_TOKEN}, dataType: 'JSON', success: function (data) { console.log(data); } });

Add error callback to your ajax request to find if an error is thrown,将错误回调添加到您的 ajax 请求中以查找是否抛出错误,

$.ajax({
  type    :"POST",
  url     :"http://localhost/laravel/public/form-data",
  dataType:"json",
  data    :{ data1:data },
  success :function(response) {
    alert("thank u");
  },
  error: function(e) {
    console.log(e.responseText);
  }
});

its better to use console.log() to see detailed information even if the response is a json string.即使响应是 json 字符串,最好使用 console.log() 来查看详细信息。 Try the code and let us know if something is logged to the browser console尝试代码并让我们知道是否有内容记录到浏览器控制台

Your jQuery code has syntax error in success callback, that's why its not making any post request to Laravel, please try below javascript it will work您的 jQuery 代码在success回调中有语法错误,这就是为什么它没有向 Laravel 发出任何post请求,请在下面的 javascript 中尝试它会起作用

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <select> <option data-id="a" value="a">a</option> <option data-id="b" value="b">b</option> <option data-id="c" value="c">c</option> </select> <script type="text/javascript"> $(function () { $('select').on('change', function (e) { var data = $(this).children('option:selected').data('id'); $.ajax({ type :"POST", dataType:"json", url :"http://localhost/laravel/public/form-data", data :{ data1:data }, success :function(response) { alert("thank u"); } }); }); }) </script>

In Laravel , you can just return array or object and it will automatically convert it to json response在 Laravel 中,你可以只返回arrayobject ,它会自动将其转换为json响应

return ['success' => true, 'data' => $data];

You made error in code ,please write it properly.您在代码中犯了错误,请正确编写。

$.ajax({
    type    :"POST",
    url     :"http://localhost/laravel/public/form-data",
    dataType:"json",
    data    :{ data1:data },
    success :function(response){
    alert("thank u");
    }
});

Update更新

I just saw your Returning datatype is json , so use我刚刚看到你的返回数据类型是 json ,所以使用

 dataType:"json",

or或者

 dataType:"jsonp",

The problem was type should be "GET" instead of "POST" and问题是类型应该是“GET”而不是“POST”

route get('form-data', 'FormController@postform');

Thank U every one for your help谢谢大家的帮助

如果您发送所有表单数据则更好,然后在 ajax 中使用data: $(this).serialize() ,并在表单内部使用{{ csrf_field() }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM