簡體   English   中英

無法使用AJAX將變量發布到PHP

[英]Can't post variable to PHP using AJAX

我正在嘗試使用JavaScript將變量發送到PHP,但是卻沒有任何響應。 有任何想法嗎?

PHP / HTML:

    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
      <script src="dashmenu.js"></script>
    </head>

    <body>
      <?php
        $selection = $_POST['selection'];
        if($selection == 'profile'){
      ?>
      <p> it works
      <?php
        }
      ?>

      <button id="button"> profile </button>
    </body>

JS檔案(dashmenu.js):

$('#button').click(function() {
    var menuSelection = "profile";

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

在您的html文件中(假設為index.html),您可以:

$('#button').click(function() {
  var menuSelection = "profile";

  $.ajax({
    type: 'POST',
    dataType: "html",
    url: 'dashboard.php',
    data: {selection: menuSelection},
    success: function(response) {
        alert(response);
    },error: function(jqXHR, textStatus, errorThrown){
        alert('Error: ' + errorThrown);
    }
  });
});

在dashboard.php中,您僅應具有處理請求並返回(回顯)所需輸出的代碼:

<?php
    $selection = $_POST['selection'];
    if($selection == 'profile'){
        echo "It works";
    }else{
        echo "It failed";
    }
?>

$('#button')。click(function(){var menuSelection =“ profile”;

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

});

在瀏覽器的控制台中運行此命令。 右鍵單擊>控制台選項卡。 如果要檢查此功能是否已成功綁定到按鈕。 如果您的瀏覽器返回“成功”警報,則意味着您錯誤地包含了它。

如果單擊時沒有任何反應,請在$ .ajax()中包括.fail()

看起來像這樣:

 $.ajax({
   type: 'POST',
   url: 'dashboard.php',
   data: {
    selection: menuSelection
    },
   success: function(response) {
    alert(response);
   },
  error: function(jqXHR, textStatus, errorThrown){

  }
 });

暫無
暫無

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

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