Javascript 将AJAX变量传递到.php页面并加载该页面和echo变量
简单问题: 我只想将Javascript 将AJAX变量传递到.php页面并加载该页面和echo变量,javascript,php,ajax,Javascript,Php,Ajax,简单问题: 我只想将item_num发送到insert_profile.php,然后加载insert_profile.php并在那里回显item_num。它不起作用了insert_profile.php'将加载,但无法获取数据 我的数据有问题吗:?我还尝试了数据:{item\u num:item\u num}。如果这是重复的话,我很抱歉,但是我已经尝试了我看到的所有示例,没有一个是有效的。我想它也可能出现在success: 我也看过 Javascript/HTML <script>
item_num
发送到insert_profile.php,然后加载insert_profile.php并在那里回显item_num
。它不起作用了insert_profile.php'将加载,但无法获取数据
我的数据有问题吗:
?我还尝试了数据:{item\u num:item\u num}
。如果这是重复的话,我很抱歉,但是我已经尝试了我看到的所有示例,没有一个是有效的。我想它也可能出现在success:
我也看过
Javascript/HTML
<script>
$('.prof_wl_btn').click(function() {
$(this).removeClass('prof_wl_btn');
$(this).addClass('prof_wl_btn_added');
var item_num = this.id;
alert('item id ' + item_num); //*this will alert correctly*
$.ajax({
type: "POST",
url:'insert_profile.php',
data: "item_num"+item_num,
success: location.href = "insert_profile.php" //*this will load**
});
});
</script>
$('.prof_wl_btn')。单击(函数(){
$(this.removeClass('prof_wl_btn');
$(this.addClass('prof_wl_btn_added');
var item_num=this.id;
警报('item id'+item_num);//*这将正确警报*
$.ajax({
类型:“POST”,
url:'insert_profile.php',
数据:“项目数量”+项目数量,
成功:location.href=“insert_profile.php”//*这将加载**
});
});
PHP
<?php
$s_n = $_REQUEST['item_num'];
echo $s_n;
?>
在PHP代码中,您可以这样做并检查
<?php
echo 'OK';
您不能以这种方式回显变量,因为您对同一页面有两个不同的请求:
- 第一个是AJAX请求,当您将数据发送到您的页面,在那里执行一些操作并返回数据时李>
- 第二个是当您访问
insert_profile.php
页面时,当您的值丢失时
如果您希望看到您的值得到响应,可以执行以下操作:
AJAX调用应该如下所示:
$.ajax({
type: "POST",
url:'insert_profile.php',
data: {item_num : item_num},
success : function(data) {
alert(data);
}
});
然后是您的PHP文件:
<?php $s_n = $_POST['item_num'];
echo $s_n;
exit;
?>
@user2118228您在数据中缺少=
:“item_num”+item_num
,成功应该是一个函数。或者用简写法,您可以使用$.post(“insert_profile.php”,“item_num”:item_num},function(){location.href=“insert_profile.php”)
我在,它仍然没有回显变量。@user2118228检查我的更新答案,然后再试一次。我不太了解PHP
,但是PHP代码不应该使用$\u POST
而不是$\u REQUEST
?那么我可以将它放入$\u SESSION
变量中吗?或者我能做什么?是的,你可以把它放在一个会话变量上。上面的代码会正确地回显,但是我怎样才能让数据从insert\u profile.php
中回显出来呢?我试着输入一个$\u会话
变量,但它不起作用。我尝试了$\u会话['var']=$s\n;echo$_会话['var']代码>我是否必须将其放入会话
中,然后再从那里重新定向?您需要在哪里回显它?在发出AJAX请求的同一页面上,或者在进入页面insert_profile.php
时?无论如何,如果您有一个用于AJAX请求的文件,最好只用于AJAX请求,而不是直接访问它;如果($_POST){$s_n=$_POST['item_num'];$_SESSION['var']=$s_n;}其他{echo$_SESSION['var'];}
<?php $s_n = $_POST['item_num'];
echo $s_n;
exit;
?>