无法使用AJAX将变量发布到PHP

时间:2016-05-19 19:45:43

标签: javascript php jquery html 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');
        }
    });
});        

2 个答案:

答案 0 :(得分:0)

在你的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";
    }
?>

答案 1 :(得分:0)

$(&#39;#button&#39;)。click(function(){     var menuSelection =&#34; profile&#34 ;;

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

});

在浏览器的控制台中运行此功能。 右键单击&gt; Console选项卡。 如果要检查此功能是否已成功绑定到该按钮。如果您的浏览器让您重新获得成功&#39;警报,这意味着你错误地包含它我猜。

如果您点击时没有任何反应,请在$ .ajax()中包含.fail()

这将是这样的:

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

  }
 });