当我试图在同一页面上发送价值时,我有点困惑.
<script>
$("select[name='sweets']").change(function () {
var str = "";
$("select[name='sweets'] option:selected").each(function () {
str += $(this).text() + " ";
});
jQuery.ajax({
type: "POST",data: $("form#a").serialize(),success: function(data){
jQuery(".res").html(data);
$('#test').text($(data).html());
}
});
var str = $("form").serialize();
$(".res").text(str);
});
</script>
<div id="test">
<?PHP
echo $_POST['sweets'];
?>
</div>
<form id="a" action="" method="post">
<select name="sweets" >
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option>Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
</form>
好吧,如果它位于html标签的顶部,它将显示,但如果它在体内,它将显示为null.
解决方法
这是适合您的工作代码.要将ajax请求发送到同一页面,您可以将url参数保持为空,这是您已经在做的.如果你试图让$_POST有值时脚本的行为不同,那么就像我在下面使用的那样使用isset.
<?PHP
if(isset($_POST['sweets']))
{
echo $_POST['sweets'];
exit;
}
?>
<script>
$(function(){
$("select[name='sweets']").change(function () {
var str = "";
$("select[name='sweets'] option:selected").each(function () {
str += $(this).text() + " ";
});
jQuery.ajax({
type: "POST",success: function(data){
jQuery(".res").html(data);
$('#test').html(data);
}
});
var str = $("form").serialize();
$(".res").text(str);
});
});
</script>
<div id="test">
</div>
<form id="a" action="" method="post">
<select name="sweets" >
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option>Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
</form>