简体   繁体   English

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

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

I am trying to send a variable to PHP using JavaScript but I don't get any response whatsoever. 我正在尝试使用JavaScript将变量发送到PHP,但是却没有任何响应。 Any ideas? 有任何想法吗?

PHP/HTML: 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 file (dashmenu.js): JS档案(dashmenu.js):

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

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

In your html file (let's say index.html) you could have: 在您的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);
    }
  });
});

In your dashboard.php, you should ONLY have code that processes requests, and returns (echoes) the desired output: 在dashboard.php中,您仅应具有处理请求并返回(回显)所需输出的代码:

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

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

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

}); });

Run this in your console in your browser. 在浏览器的控制台中运行此命令。 Right-click > Console tab. 右键单击>控制台选项卡。 If you want to check whether this function has successfully bind to the button. 如果要检查此功能是否已成功绑定到按钮。 If your browser returns you 'success' alert, meaning you include it wrongly I guess. 如果您的浏览器返回“成功”警报,则意味着您错误地包含了它。

If nothing happen when you click, please include .fail() in your $.ajax() 如果单击时没有任何反应,请在$ .ajax()中包括.fail()

Which will look like this: 看起来像这样:

 $.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