从jQueryAjax向PHP传递一个值

Passing a value to PHP from jQuery Ajax

本文关键字:一个 jQueryAjax PHP      更新时间:2023-09-26

我正在尝试将一个值返回到PHP,并将其发送到数据库。使用jQueryAJAX的GET类型,我似乎无法做到这一点。以下是我用来获取值的PHP:

<?php require_once("header.php"); ?>
<?php require_once("class.php"); ?>
<?php
//$month = $_POST['month'];
//$year = $_POST['year'];
$month = 8;
$year = 2013;
$numDays = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$empty = "<table class='box'><td>&nbsp</td></table>";
$cal = new calendar();
$cal->mkMonth($month);
$cal->emptyDays($empty, $numDays, $month, $year);
$cal->mkdays($numDays, $month, $year);
echo "</div>";

echo "<div id='jresult'>";
if (isset($_GET['id'])) {
   echo ($_GET['id']);
}
echo "</div>";
?>

这是jQuery。。。

$(document).ready(function(){
    $(".box").mouseenter(function(){$(this).css("background-color", "red");});
    $(".box").mouseout(function(){$(this).css("background-color", "transparent");});
    $(".box").click(function() {
        date_time = $(this).attr('id');
        console.log(date_time);
        $.ajax({
            type: 'GET',
            url: '/book.me/loop.php',
            data: "id=" + $(date_time).val(),
            success: function(data){
                alert('successful');
            }
        });
    });
});

我试图将.box类元素的id传递给date_time变量,这是有效的,但当我在PHP中调用$_GET['id']时,它似乎不起作用。我只是得到一个未定义的值。

如果你想发送id属性,而不是值,你可以使用

$(".box").click(function() {
    date_time = $(this).attr('id');
    $.ajax({
        type: 'GET',
        url: '/book.me/loop.php',
        data: "id=" + date_time,
        success: function(data){
            alert('successful');
        }
    });
});

您可以使用$(this):引用单击的.box

$(".box").click(function() {
    $.ajax({
        type: 'GET',
        url: '/book.me/loop.php',
        data: {
            id: $(this).val()
        },
        success: function(data){
            alert('successful');
        }
    });
});

您应该这样设置数据:

$(".box").click(function() {
    $.ajax({
        type: 'GET',
        url: '/book.me/loop.php',
        data: "id=" + this.id,
        dataType: 'html',
        data: { id: $(this).val() },
        success: function(data){
            alert('successful');
        }
    });
});

试试这个:

$('#' + date_time).val()