我正在尝试使用AJAX将变量从JavaScript传递给PHP,但我无法这样做。每当我尝试var_dump($ _ POST ['winner_id'])时,它返回NULL。我试图用Chrome中的开发者工具检查AJAX调用,它显示 winner_id:0 - 这是正确的。
这是我的代码:
function ajaxCall() {
alert("To AJAX: the winnerid is: "+winner_id);
$.ajax
( {
type: "POST",
url: "ajax.php",
data: {winner_id : winner_id},
success: function(response)
{ alert("The winner was passed!")}
}
);
};
ajaxCall();
<?php
session_start();
if(isset($_POST['winner_id']))
{
$winner_id = $_POST['winner_id']."";
var_dump($winner_id);
}
var_dump($_POST['winner_id']);
?>
如果我在PHP脚本的开头做var_dump($_POST)
,那么它会给我array(0) { }
我是网络开发的新手,现在已经尝试了几个小时。任何提示都将非常感激。谢谢!
答案 0 :(得分:2)
您在哪里初始化winner_id。您必须将其作为参数传递或将其初始化为全局变量。
function ajaxCall(winner_id) {
alert("To AJAX: the winnerid is: "+winner_id);
$.ajax
({
type: "POST",
url: "ajax.php",
data: {"winner_id" : winner_id},
success: function(response)
{
alert("The winner was passed!");
}
});
};
ajaxCall(winner_id);
答案 1 :(得分:0)
您从哪里开始winner_id
的价值?像
function ajaxCall() {
var winner_id = '123';
...
或者如果您在致电winner_id
之前发起了ajaxCall()
,则应使用ajaxCall()
之类的参数调用ajaxCall($winnerid)
,$winnerid
来自您的PHP
然后
function ajaxCall(winner_id) {
...
答案 2 :(得分:0)
我猜你必须将你的winner_id转换为字符串,因为php将零(0)视为空
function ajaxCall() {
alert("To AJAX: the winnerid is: "+winner_id);
$.ajax
( {
type: "POST",
url: "ajax.php",
data: {winner_id : winner_id.toString()},
success: function(response)
{ alert("The winner was passed!")},
dataType: "json"
}
);
};
ajaxCall();