我会尽量简单地描述它。
我有这个HTML:
<fieldset class="ui-field-contain">
<select name="localita" id="localita" onchange="cambia()">
<option value="Tutti">Tutti</option>
<option value="Location 1">Location 1</option>
<option value="Location 2">Location 2</option>
<option value="Location 3">Location 3</option>
</select>
</fieldset>
连接到此javascript:
<script>
function cambia() {
$.post("switch_localita.php", {
localita : $("#localita").val()
}).done(function(data) {
});
}
</script>
连接到这个php文件:
$localita = $_POST['localita'];
switch ($localita) {
case "Location 1" :
$sql = "my query";
$result = mysqli_query($con, $sql) or die("Query error: " . mysqli_error());
$records = array();
while ($row = mysqli_fetch_assoc($result)) {
$records[] = $row;
}
mysqli_close($con);
echo json_encode($records);
break;
case "Location 2" :
//my stuff
break;
case "Location 3" :
//my stuff
break;
default :
//mystuff
}
最后我用这个ajax / json检索:
<script type="text/javascript">
$.ajax('switch_localita.php', {
dataType : "json",
jsonp : "jsoncallback",
method : 'post',
contentType : 'application/json',
success : function(data, status) {
$.each(data, function(i, item) {
//my stuff
});
},
error : function(xhr, d, s) {
$('#output').empty().html(s);
}
});
</script>
问题是:我如何使这一切工作? 我需要的是,一旦选择内容发生变化(选择另一个语音),表单就会被提交,并从存储在php文件中的开关案例中检索正确的查询。此外,我需要在打开页面时显示标准查询(因此,如果您打开页面,您还没有选择语音,但无论如何都会加载查询。)。
谢谢
答案 0 :(得分:1)
继承了json编码和$ get ajax的更新版本。
这是你的HTML
<fieldset class="ui-field-contain">
<select name="localita" id="localita"">
<option value="Tutti">Tutti</option>
<option value="Location 1">Location 1</option>
<option value="Location 2">Location 2</option>
<option value="Location 3">Location 3</option>
</select>
</fieldset>
<div class="the-return"></div>
我为要打印的数据添加div。
这是你的ajax
$(function(){
$("#localita").change(function() {
var sVal = $(this).val();
if (sVal !== "NA") { // I am assuming you don't want to make an ajax call when the value is 'NA'!
$.getJSON("response.php", {localita: $(this).val()}, function(result) {
$(".the-return").html(
"Your Location : " + result //this is where u decide how ur data going to be printed
);
alert(result);
});
//by the way $(this).val() = id1|id2|id3
}
});
})
这是你的PHP。
<?php
$localita = $_GET['localita'];
switch ($localita) {
case "Location 1" :
$sql = "my query";
$result = mysqli_query($con, $sql) or die("Query error: " . mysqli_error());
$records = array();
while ($row = mysqli_fetch_assoc($result)) {
$records[] = $row;
}
mysqli_close($con);
echo json_encode($records);
break;
case "Location 2" :
//my stuff
break;
case "Location 3" :
//my stuff
break;
default :
//mystuff
}
?>
此代码基于此问题的答案= JSON not working with OnChange event
希望它适合你。