将AJAX变量传递到.php页面并加载该页面和echo变量


Passing AJAX variable into .php page and load that page and echo variable

简单问题:我只想将item_num发送到insert_profile.php,然后加载insert_profile.php并在那里回显item_num。它不起作用!"insert_profile.php"将加载,但它没有获取数据。

我的data:有问题吗?我也试过data: {item_num: item_num}。如果这是重复的,我很抱歉,但我已经尝试了我看到的所有例子,但都不起作用。我认为它也可能在success:

我也看过http://api.jquery.com/jQuery.ajax/.

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>

PHP

<?php
$s_n = $_REQUEST['item_num'];
echo $s_n;
?>

您不能以这种方式回显变量,因为您对同一页面有两个不同的请求:

  • 第一个是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;
?>
$.ajax({
      type: "POST",
      url:'insert_profile.php',
      data: "item_num = "+item_num,   
      success : function( data ) {
         // location.href = "insert_profile.php" //*this will load** 
         alert(data);  
      }
  });

在PHP代码中,你喜欢这样做并检查

<?php
echo 'OK';