Home > Article > Backend Development > javascript - How to get background data through ajax based on drop-down menu selection without refreshing the page
I want to use a set of drop-down menus, and then when selecting one of them, filter out the list that meets the conditions based on the selected list title and display it on the page below. How can I implement the code?
Reply content:
<code>$('select').change(function(){//监控select的change事件 var dom = document.getElementById('id'), data = dom.options[dom.selectedIndex].value;//选中的option的value; ajax({}); });</code>
There are roughly the following steps:
drop-down menu (ID/title, usually the ID will be obtained, and go to the background to obtain the corresponding data from the database based on this ID)
<code><script type="text/javascript"> $("select").change(function() { var title = $(this).text(); // 1、获取选择下拉框的标题 //var id = $(this).val(); 获取选中的ID值 var url = ""; //这里填写后端的url $.ajax({ //2、发送给后端 url: url, type: 'POST', //设置发送的方式 这里假设为POST dataType: 'html', //返回的数据类型 data: {title: title}, //把选中的标题发给后端 success:function(data) { // 4、这里写成功后更新页面的操作 } }) }); </script></code>
<code><?php $title = $_POST['title']; //接收参数 选中的ID或者标题 //3、根据这个标题或者ID 去数据库查询匹配到的相关的内容 然后根据需求组装成html格式 echo $html; //返回给前端 exit;</code>
<code>1、ajax请求后端接口,接口返回数据。(一般返回json) 2、ajax在回调函数里面,解析数据。 3、把数据写到页面,看你情况用html还是append</code>
Such a broad question; first understand the following "js template";
<code>$("select").onchange(function(){ console.log($(this).val());//这里的this.val 就是当前选中的option的val 根据这个val 进行逻辑判断 })</code>It is recommended to write a function in the log and pass the value to perform logical operations
The answers above are all very good, it’s nothing more than the onchange event of javascript