gpt4 book ai didi

javascript - 将 JavaScript 变量发送到 PHP

转载 作者:行者123 更新时间:2023-12-01 00:06:22 27 4
gpt4 key购买 nike

所以我试图将日期存储在数据库中,为此我需要将变量“date”传递给 PHP 文件 store.pro.php 但是,我不知道如何去做这个。我尝试过 Ajax,但目前它似乎不起作用。

Javascipt 代码:

// variables for fetching current date
n = new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();

// variables for displaying current date
let displayDay = 0;
let displayMonth = 0;

// If m or d are only one digit, add a leading 0 to the value
if (d < 10) {
displayDay = '0' + d.toString();
} else {
displayDay = d.toString();
}

if (m < 10) {
displayMonth = '0' + m.toString();
} else {
displayMonth = m.toString();
}

// storing the current date within raceDate
var date = displayDay + '/' + displayMonth + '/' + y;

$.ajax({
url: "processes/store.pro.php",
type: "POST",
data: { x: date }
});

store.pro.php中的PHP代码

if (isset($_POST['x'])) {
$raceDate = $_POST['x'];

echo($raceDate);
} else {
echo "no";
}

最佳答案

你怎么知道“它似乎不起作用”?

将 success 方法添加到您的 ajax 中,如下所示:

$.ajax({
url: "processes/store.pro.php",
type: "POST",
data: { x: date },
success: function(res) {
res = JSON.parse(res);
console.log(res);
}
});

然后,在 store.pro.php 中输入:

if (isset($_POST['x'])) {
$raceDate = $_POST['x'];

echo json_encode($raceDate);
} else {
echo json_encode("no");
}
exit; // You may need remove this line, after you check, that ajax call is working

并检查浏览器中的控制台

关于javascript - 将 JavaScript 变量发送到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60353676/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com