简体   繁体   English

即使使用 .on,Ajax 调用也只能工作一次

[英]Ajax call only works once even with .on

I have been trying for the last two weeks on and off to get my Ajax call to work more than once, I'm self taught and trying my best to figure things out myself, but this problem is killing me.在过去的两周里,我一直在断断续续地尝试让我的 Ajax 调用工作不止一次,我是自学的,并尽我所能自己解决问题,但这个问题正在杀死我。 Some people with the same problem used .on and it seemed to work for them, but I can still only get it to work once.一些有同样问题的人使用 .on 并且它似乎对他们有用,但我仍然只能让它工作一次。

The idea is for a user to click a button on the page, for which they are awarded with XP.这个想法是让用户点击页面上的一个按钮,他们会因此获得 XP。

 <div id="AJTestt">Ajax Test</div> <script> $(document).on('click', "#AJTestt", function($id, $SkillOne, $XP) { $id = <?php if(isset($_SESSION['id'])) echo $_SESSION['id']; ?>; $SkillOne = <?php if(isset($SkillOne)) echo $SkillOne; ?>; $XP = 3; //get the input value $.ajax({ url: "ax.php", cache: "false", data: {id : $id, SkillOne: $SkillOne, XP: $XP}, dataType: 'text', type: "POST", success: function(data){ console.log("Success"); console.log(data); history.back(); //Just to remove the ax.php bit }, error: function(){ console.log("Error"); console.log(data); } }); }); </script>

//////// PHP code (ax.php) //////// PHP 代码 (ax.php)

 <?php require_once 'resource/Database.php'; $id = $_POST['id']; $SkillOne= $_POST['SkillOne']; $XP = $_POST['XP']; echo "$id \\n"; echo "$SkillOne \\n"; echo "$XP \\n"; if($XP==1){ $SkillOne = $SkillOne +1; } else if($XP==2){ $SkillOne = $SkillOne +2; } else if($XP==3){ $SkillOne = $SkillOne +3; } $sqlUpdate = "UPDATE users SET SkillOne =:SkillOne WHERE id =:id"; $statement = $db->prepare($sqlUpdate); $statement->execute(array(':SkillOne' => $SkillOne, ':id' => $id)); echo $SkillOne; ?>

Everything works fine first time, the console displays (for testing purposes): -Success -ID -Old Xp -Xp to be added -New Xp第一次一切正常,控制台显示(用于测试目的): -Success -ID -Old Xp -Xp to be added -New Xp

But if I click the same button again it displays the exact same values in the console.但是如果我再次单击同一个按钮,它会在控制台中显示完全相同的值。

Any help would be much appreciated, Kind Regards Wings任何帮助将不胜感激,亲切的问候翅膀

I'm thinking it's as simple as this but I could be wrong.我想就这么简单,但我可能是错的。

The click function creates an event object and makes it available like this, so you cannot pass variables/data to the function in the way you have: click 函数创建一个event对象并使其可用,因此您不能以您拥有的方式将变量/数据传递给函数:

.on('click', '#myElement', function(event) {
    event.preventDefault();
});

You can pass data/a variable to the function like this (see dataVariable ):您可以像这样将数据/变量传递给函数(请参阅dataVariable ):

.on('click', '#myElement', dataVariable, function(event) {
    doSomethingWith(dataVaraible);
});

If you really need to pass data to the handler then you could put $id , $SkillOne and $XP in an object and give the object to the handler:如果您确实需要将数据传递给处理程序,那么您可以将$id$SkillOne$XP放在一个对象中,并将该对象提供给处理程序:

var data = { id: 1, skillOne: 'blah', xp: 100 };

.on('click', '#myElement', data, function(event) {
    doSomethingWith(data);
});

But I don't think you need to pass anything to the function, you can just use them inside anyway like this但我认为你不需要向函数传递任何东西,你可以像这样在内部使用它们

<script>
$(document).on('click', "#AJTestt", function() {    
    var $id = <?php if(isset($_SESSION['id'])) echo $_SESSION['id']; ?>,
        $SkillOne = <?php if(isset($SkillOne)) echo $SkillOne; ?>,
        $XP = 3;

        //get the input value
        $.ajax({
            url: "ax.php",
            cache: "false",
            data: {id : $id, SkillOne: $SkillOne, XP: $XP},
            dataType: 'text',
            type: "POST",
            success: function(data){
                console.log("Success"); 
                console.log(data); 
                history.back(); //Just to remove the ax.php bit
            },
            error: function(){
                    console.log("Error"); 
                    console.log(data); 
            }
        });
        });
 </script>

I am going to propose you the following solution.我将向您提出以下解决方案。 Such solution would be based upon what I have understood of your post.这种解决方案将基于我对您的帖子的理解。 Let me know if it does not adjust.如果它不调整,请告诉我。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <button id="mybutton">Press Me to gain XPs</button>
</body>
<script>
$(document).ready(function(){
    $("#mybutton").click(function(){
        $.ajax({
            url: "ax.php",
            cache: "false",
            dataType: 'text',
            type: "POST",
            success: function(data){
                console.log("Success"); 
                console.log(data); 
                history.back(); //Just to remove the ax.php bit
            },
            error: function(){
                    console.log("Error"); 
                    console.log(data); 
            }
        });
    });
});
</script>
</html>

For the backend, I'd do this:对于后端,我会这样做:

<?php

    if (! isset($_SESSION['id'])) {
        return;
    }

    $pdo = new PDO("mysql:host=127.0.0.1;dbname=yourdb", 'root', 'password');
    // change according to your id type
    $sql = sprintf("SELECT user_xp FROM users WHERE id=%d", $_SESSION['id']);

    $retrieved_info = $pdo->query($sql);

    $current_xp;
    if ($retrieved_info) {
        $info = $retrieved_info->fetchAll(PDO::FETCH_ASSOC);
        $current_xp = $info[0]['user_xp'];
    }


    if ($current_xp == 1) {
        $pdo->exec("UPDATE users SET user_xp=%d WHERE id=%d", $current_xp+1, $_SESSION['id']);
    } // and so on....

    echo $current_xp;

?>

Let me know whether this is what you needed & it's working.让我知道这是否是您需要的并且它正在工作。

You're getting the same values from the server every time because you're passing the same values to the server every time:你从服务器,因为你每次都传递相同的值服务器的每一次得到同样的价值观:

$(document).on('click', "#AJTestt", function($id, $SkillOne, $XP) {    
    $id = <?php if(isset($_SESSION['id'])) echo $_SESSION['id']; ?>;
    $SkillOne = <?php if(isset($SkillOne)) echo $SkillOne; ?>;
    $XP = 3;
    // ...

The parameters you're trying to pass to the click handler won't do anything -- click just passes an event object, no other parameters -- and in any case you replace them immediately with fixed values.您尝试传递给点击处理程序的参数不会做任何事情——点击只是传递一个event对象,没有其他参数——在任何情况下,您都会立即用固定值替换它们。 (PHP includes are only interpreted once, on page load; they do not update in real time if the underlying data on the server changes.) (PHP 包含仅在页面加载时解释一次;如果服务器上的基础数据发生更改,它们不会实时更新。)

If you want the values to update, you need to store the data returned from the AJAX call (which if my extremely rusty PHP skills aren't misleading me appears to just be the contents of $SkillOne) in a variable so the new value can be passed to the server on the next call.如果您想要更新值,您需要将从 AJAX 调用返回的数据(如果我非常生疏的 PHP 技能不会误导我,它似乎只是 $SkillOne 的内容)存储在一个变量中,以便新值可以在下一次调用时传递给服务器。 Currently you're not doing anything with that returned value other than logging it to the console.目前,除了将其记录到控制台之外,您没有对该返回值执行任何操作。

Here, for example, the PHP-included values are set once on load in global variables (not an ideal practice, but good enough for demonstration), which can then be updated on each ajax call:例如,在这里,PHP 包含的值在加载时在全局变量中设置一次(不是理想的做法,但足以用于演示),然后可以在每次 ajax 调用时更新:

var $SkillOne = <?php if(isset($SkillOne)) echo $SkillOne; ?>; // probably need an `else` here too, for a default value
var $id = <?php if(isset($_SESSION['id'])) echo $_SESSION['id']; ?>;
var $XP = 3;

$(document).on('click', "#AJTestt", function() { 
  $.ajax({
    url: "ax.php",
    cache: "false",
    data: { id: $id, SkillOne: $SkillOne, XP: $XP },
    dataType: 'text',
    type: "POST",
    success: function(data) {
      console.log("Success");
      $SkillOne = data; // update the $SkillOne variable with the new value
      // history.back(); // Do not do this; ajax calls do not change the history stack; you'll bump the user to the page they were on previously.
    },
    error: function() {
      console.log("Error");
      console.log(data);
    }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM