gpt4 book ai didi

javascript - 如何将变量值从 JS 传递到 PHP(不通过表单)

转载 作者:行者123 更新时间:2023-11-30 06:55:12 24 4
gpt4 key购买 nike

我是新来的。所以我试图将变量值从客户端传递到 php 服务器。我查看这件事并看到了很多答案,但大多数都是关于发送表单值的。我想做的是传输实际变量值。一个非常简单的示例(以下按钮的多个实例):

 $("#aam").click(function () {
var e = confirm("Are you sure?")
if(e == true)
{
$(this).hide('slow');
counter++;
}
});

每次单击按钮时,计数器都会加一(在“if”检查之后)。假设我想获取服务器的计数器值,应该如何完成。从我的搜索中,我了解了 AJAX,但遗憾的是无法将其调整到我自己的场景中......我尝试将此作为 AJAX 请求:

$("#click_ajax").click(function() {
$.ajax({
type: 'post',
url: 'c:/xampp/htdocs/abby/test.php',
data: {counter}
});
});

使用这个 PHP:

<?php 

$counter = $_POST['counter'];

echo $counter

?>

不幸的是,它没有用——无论我做什么,我都会通过 xampp 收到“通知: undefined index :第 9 行 C:\xampp\htdocs\abby\test.php 中的计数器”错误。希望有人能帮助我。提前致谢,

艾比。

最佳答案

您没有通过 Ajax 请求发送正确的数据。试试这个:

JS:

 var ajaxUrl = 'abby/test.php';

$.ajax({
type: "POST",
url: ajaxUrl, //check if you get in the ajax file
data: {
action: "sendCounter",
counter: counter
}
}).always(function() {

}).done(function(data) {
console.log(data); // you should get back from the server the counter number
});

PHP(更优雅的 ajax 文件方式):

if (isset($_POST['action']))
{
$strAction = $_POST['action'];
switch ($strAction)
{
case 'sendCounter':
if (isset($_POST['counter']))
{
echo $_POST['counter'];
}
break;
}
}

希望这对您有所帮助。

关于javascript - 如何将变量值从 JS 传递到 PHP(不通过表单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45691237/

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