简体   繁体   English

使用select2.js发送Ajax请求

[英]using select2.js to send ajax request

I have two select elements both using selec2.js, the first select element has drop down options populated from the database, now what I want to do is to choose an option from select element 1, get the value and send that value via ajax to query the database and return matching results and populate the results in the 2nd select element. 我有两个均使用selec2.js的选择元素,第一个选择元素具有从数据库填充的下拉选项,现在我要做的是从选择元素1中选择一个选项,获取值并通过ajax将其发送到查询数据库并返回匹配结果,并将结果填充到第二个select元素中。 unfortunately, I haven't succeeded with returning data back from the server, below is my code and oh I am using laravel. 不幸的是,我还没有成功从服务器返回数据,下面是我的代码,哦,我正在使用laravel。

$('#province').on('change', function (e) {
    var data = $("#province option:selected").val();
    $.ajax({
        url: "{{route('list-townships')}}",
        type: 'get',
        data: {
            province_id: data
        },
        success: function (response) {
            console.log(response);
            response.filter(function (response) {
                if (response) {

                   //Append data to the 2nd select element

                }
            })
        },
        error: function (err) {}
    })
});

Okay, I find the issue here, due to laravel CSRF request protection I had forgotten to define the CSRF Token in the ajax header. 好的,由于laravel CSRF请求保护,我忘记了在ajax标头中定义CSRF令牌,因此在这里找到了问题。 the complete code is below. 完整的代码如下。

  $(document).ready(function() {
 $.ajaxSetup({
     headers: {
         'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
     }
 });
 $('#province').on('change', function(e) {
     var data = $("#province option:selected").val();
     console.log(data);
     $.ajax({
         url: "{{route('list-townships')}}",
         type: 'get',
         data: {
             province_id: data
         },
         success: function(response) {
             console.log(response);
             response.filter(function(response) {
                 if (response) {
                     var townships = new Option(response.name, response.id, false, false);
                     $('#township').append(townships).trigger('open');
                 }
             })
         },
         error: function(err) {}
     })
 });

}); });

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

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