我有一个显示状态的选择选项 我有一个DIV返回所选州的运输成本 我的问题是,当我选择一个选项并返回DIV的值时页面会刷新 我想显示DIV的值而不刷新整个页面
<html>
<body>
<div id ="content"> this is the cost of shipping of :
<?php
$ship=20;
if (isset($_POST['city'])){
$listings = $_POST['city'];
} else if (isset($_GET['city'])) {
$listings = $_GET['city'];
} else {
$listings = 'city';
}
switch ($listings) {
case 'California':
$ship=$ship+5; echo $ship;
break;
case 'Alabama':
$ship=$ship+10; echo $ship;
break;
case 'Texas':
$ship=$ship+15; echo $ship;
}
?>
</div>
<form id = "form1" name = "form" >
<select id ="city" name ="city" method="post" onchange="this.form.submit()" >
<option value="California" <?php echo (isset($_POST['city']) && $_POST['city'] == 'California') ? 'selected="selected"' : ''; ?>>California</option>
<option value="Alabama" <?php echo (isset($_POST['city']) && $_POST['city'] == 'Alabama') ? 'selected="selected"' : ''; ?>>Alabama</option>
<option value="Texas" <?php echo (isset($_POST['city']) && $_POST['city'] == 'Texas') ? 'selected="selected"' : ''; ?>>Texas</option>
</select>
</form>
</body>
</html>
java脚本
<script type="text/javascript" >
$("#form1").click(function(){
$("#content").load(" #content");
});
</script>
答案 0 :(得分:2)
您需要使用jquery的onchange
事件并获取select的值,然后使用ajax将其传递到您的php
页面。您需要在代码中进行的更改:
您的 html 代码:
<!--remove onchange from here-->
<select id ="city" name ="city">
<!--same code -->
</select>
您的 jquery 代码:
//onchange of select
$("#city").change(function() {
//get select value
var city = $(this).val();
console.log(city)
//ajax call
$.ajax({
url: 'urlofphppage',
type: 'POST',
data: {
'city': city
},
success: function(data) {
alert('Data: ' + data);
//add data which recieve from server to div
$("#content").html(data);
}
});
});
您的 php 页:
if (isset($_POST['city'])){
$listings = $_POST['city'];
switch ($listings) {
case 'California':
$ship=$ship+5;
echo $ship;//will send back to ajax as response
break;
case 'Alabama':
$ship=$ship+10;
echo $ship; //will send back to ajax as response
break;
case 'Texas':
$ship=$ship+15;
echo $ship; //will send back to ajax as response
}
}