在PHP同一页的jQuery阿贾克斯传递价值 [英] jQuery Ajax passing value on php same page
本文介绍了在PHP同一页的jQuery阿贾克斯传递价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是在它有点糊涂,当试图在同一页上送价值。
I am kinda confused on it, when trying to send value on the same page.
<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标签的顶部,但如果它的体内就会显示为空。
Well it will display if its in the top of html tag but if its inside the body it will display null.
推荐答案
下面是工作code为您服务。发送Ajax请求到同一个页面,你可以保持网址
参数为空,你已经在做。如果你想使脚本表现不同,当 $ _ POST
的值,那么使用使用isset
正如我下面使用。
Here is the working code for you. To send ajax request to the same page you can keep url
parameter empty, which you are already doing. If you are trying to make the script behave differently when $_POST
has value then use isset
as I have used below.
<?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",
data: $("form#a").serialize(),
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>
这篇关于在PHP同一页的jQuery阿贾克斯传递价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文