簡體   English   中英

如何從 ajax 請求中獲取數據然后在 php 條件語句中使用它

[英]how to get the data from ajax request then use it in php conditional statemtn

我想創建一個 ajax post 請求來獲取單選按鈕的值,然后在 PHP 條件語句中使用它。

到目前為止,我已經嘗試過這段代碼(所有代碼都來自一個 php 文件):

$(document).ready(function () {
    $('.radio-buttons input[type="radio"]').click(function(){
        var subject= $(this).val();

        $.ajax({
            url: 'home.php',
            type: 'POST',
            data: {
                'subject': subject
            },
            success: function(response) {
                alert(response); 
            }               
        });
    });
});
<form id="form1" method="POST" class="radio-buttons ">
     <input class="radio-filter"  type="radio" name="subject" value="A">A</input> 
     <input class="radio-filter"  type="radio" name="subject" value="B">B</input>            
</form>
if (isset($_POST['subject'])) {
    echo "Showing!";
}

當我單擊它們時,警報消息顯示單選按鈕的值,但未顯示 PHP 條件下的回顯。

您正在使用alert(subject); 正如您提到的那樣,它只會提醒單選按鈕的值。

將該行更改為alert(response); 提醒響應成功。

alert(subject)需要是alert(response)

alert(subject)更改為alert(response) ,因為“主題”是您已發送的內容! 因此,在“主題”之后,您的 PHP 進程將收到並作為響應返回(echo "Showing" )關於 function 和 object success: function(response)並提醒響應以查看數據/文本“正在顯示”

$(document).ready(function () {
$('.radio-buttons input[type="radio"]').click(function(){
    var subject= $(this).val();

    $.ajax({
        url: 'home.php',
        type: 'POST',
        data: {
            'subject': subject
        },
        success: function(response) {
            alert(response); 
        }               
    });
});

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM