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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28599638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:04:05  来源:igfitidea点击:

Using Ajax and returning json array in laravel 5

javascriptjqueryajaxjsonlaravel-5

提问by sujit prasad

enter image description hereI 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-dataand {{Url::route('form-data')}}.

我还尝试仅使用form-data和更改 ajax 的 URL {{Url::route('form-data')}}

回答by sunil sah

Laravel 5 uses csrf token validation for security reasons....try this...

Laravel 5 出于安全原因使用 csrf 令牌验证......试试这个......

  1. In 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');
    $.ajax({
        url: '/form-data/',
        type: 'POST',
        data: {_token: CSRF_TOKEN},
        dataType: 'JSON',
        success: function (data) {
            console.log(data);
        }
    });
    
  1. 在routes.php

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

    <meta name="csrf-token" content="{{ csrf_token() }}" />
    
  3. 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);
        }
    });
    

回答by Ashik Basheer

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. Try the code and let us know if something is logged to the browser console

即使响应是 json 字符串,最好使用 console.log() 来查看详细信息。尝试代码并让我们知道是否有内容记录到浏览器控制台

回答by Saqueib

Your jQuery code has syntax error in successcallback, that's why its not making any postrequest to Laravel, please try below javascript it will work

您的 jQuery 代码在success回调中有语法错误,这就是为什么它没有post向 Laravel发出任何请求,请在下面的 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 arrayor objectand it will automatically convert it to jsonresponse

在 Laravel 中,您可以只返回arrayobject它会自动将其转换为json响应

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

回答by sujit prasad

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

谢谢大家的帮助

回答by Pratik

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",

回答by Vipin

Better if you are sending all form data then use data: $(this).serialize() in ajax, and inside form use {{ csrf_field() }}

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