Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/471.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
Javascript 如何使用select2初始化默认值并触发ajax请求(select2:select)?_Javascript_Jquery_Jquery Select2 - Fatal编程技术网

Javascript 如何使用select2初始化默认值并触发ajax请求(select2:select)?

Javascript 如何使用select2初始化默认值并触发ajax请求(select2:select)?,javascript,jquery,jquery-select2,Javascript,Jquery,Jquery Select2,我希望在加载页面时默认选择selectbox的第一个元素。它已被选中,但不发出ajax请求。我想让它触发“select2:select”事件。只有selectbox中选定的部分发生更改,它不会执行ajax请求。当我分配第一个元素时,我希望它像“select2:select”一样工作。因此,当我选择第一个元素时,它应该在ajax请求中触发 // the part where I select the first element by default. The part that doesn't w

我希望在加载页面时默认选择selectbox的第一个元素。它已被选中,但不发出ajax请求。我想让它触发“select2:select”事件。只有selectbox中选定的部分发生更改,它不会执行ajax请求。当我分配第一个元素时,我希望它像“select2:select”一样工作。因此,当我选择第一个元素时,它应该在ajax请求中触发

// the part where I select the first element by default. The part that doesn't work as I want
$('select[name=items]').prop('selectedIndex', 1).trigger('change.select2');

// For event being selected in selectboxt
$('select[name=items]').on('select2:select', function (e) {
        $.ajax({
                "url":'myendpoint',
                "headers": {
                        
                },
                "method": "GET",
                "success": function (data) {
                     
                 //my operations
              })

})


您可以使用
change
事件执行此操作,当您执行
trigger('change')
或使用
.trigger(“select2:select”)
来触发
select2:select
事件时,此操作将被触发

演示代码

$('select[name=items]')。选择2({
宽度:“100px”
});
//使用变更事件的其他方法
$('select[name=items]')。关于('change',函数(e){
console.log(“我在chnge里面”)
//您的ajax调用
})
//使用select:2
$('select[name=items]')。在('select2:select',函数(e){
log(“我在seclet中”)
//您的ajax调用
})
$('select[name=items]').prop('selectedIndex',1.trigger('change').trigger('select2:select')//同时触发两个

1.
2.
3.

我遇到这样的情况;触发过程正常,但这次e.params未定义并出现错误。您需要使用
e.params.data
?您可以传递所选值和其他值,如。是的,我需要获取所选值,但为什么我需要发送e.params?我告诉你当它已经被选中时该怎么做。我只想通过单击鼠标对代码执行我选择的操作。不能用Jquery触发这一点让我非常恼火。我无法再次发送e.params,因为它是一个通用的运行结构。您解决了该问题吗?是的,我解决了。你发送的链接非常有用。谢谢:)