将PHP变量传递给Ajax并发布它们

时间:2014-05-28 18:53:42

标签: javascript php jquery ajax

我如何将PHP变量传递给AJAX我尝试使用var sStr = "<?php echo $game ?>.";它会将其打印出来,但我无法将其POST传递给它PHP文件。这是我的代码。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<?php
$game=$_GET['id']; 
?>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $.post("php.php",
    {
      game:"<?php echo $game; ?>",
      city:"Duckburg"
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>
</head>
<body>

<button>Add to Favourites</button>

1 个答案:

答案 0 :(得分:0)

尝试按ID调用该按钮并使用addslashes

过滤引号
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<?php
$game = $_GET['id'];
$game = addslashes($game);
?>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
  $("#button").click(function(){
    $.post("php.php",
    {
      game:"<?=$game?>",
      city:"Duckburg"
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>
</head>
<body>

<button id="button">Add to Favourites</button>