我想要从下拉列表中读取值并将其发送到同一页面的解决方案,使用GET方法。我认为ajax和jquery将实现这一点。
若我从下拉列表中选择"住院病人",那个么它会自动出现在同一页面上。
<div id="div_for_patienttype">
Choose patient type:<select id="select_patient_id"name="patient_type">
<option >Select patient type</option>
<option value="InPatient">InPatient</option>
<option value="OutPatient">OutPatient</option>
</select>
</div>
我对此进行了编码,工作正常,但有一个问题是,当我选择患者类型时,页面会被刷新,下拉列表中的值是"选择患者类型"。我实际上希望下拉列表的值保持不变,即被选中。
代码:
$(document).ready(function(){
$("#select_patient_id").change(function(){
var selected_patient=$(this).val();
sendType(selected_patient);
});
});
function sendType(type)
{
$.ajax({
type:"GET",
url:"dispres.php",
data:({patientType:type}),
success:function(success)
{
window.location.href="dispres.php?patientType="+type;
}
});
}
如何优化这个jquery和ajax代码?
读取下拉值的基本jQuery:
var patient_type = $('select[name="patient_type"]').val(); // value on submit
基本获取请求:
$.get( "my_page.php", { patient_type : patient_type } );
不确定您实际想要什么。我相信在更改下拉选择时,您希望调用一个web方法(服务)。
//代码尚未测试
$(document).ready(function(){
$("select[name=patient_type]").change(function(){
var selected_patient = $("select[name=patient_type]").val();
$.ajax({
type: "GET",
url: "process-request.php?patient="+selected_patient
}).done(function(data){
//do something
});
});
});
或者你可以写
$(document).ready(function(){
$("select[name=patient_type]").change(function(){
var selected_patient = $("select[name=patient_type]").val();
$.ajax({
type: "GET",
url: "process-request.php",
data:{patient:selected_patient}
}).done(function(data){
//do something
});
});
});
在PHP方面,基于您正在使用的框架,只获取查询字符串值
假设您正在尝试使用选项值作为参数发出GET请求
$('select[name="patient_type"]').on('change', function(){
var selected = $('select[name="patient_type"]').find(':selected').val();
$.ajax({
url: window.location.href + '?' + selected,
type: 'GET'
success:function(data) {
handleData(data);
}
});
});
function handleData(data){
// do something here with the data obtained from your get request
}