将值从 jQuery 传递到 PHP 的最佳方式

Sew*_*ryn -7 php jquery

我想知道如何将值从 Jquery 传递到 PHP。我发现了类似的代码,但其中一个都不起作用。每次警报都会显示变量的值,但是当我打开站点时却没有。Var_dump 显示 $_POST 为空。我的想法用完了你有什么吗?

jQuery代码:

$("#password-button").click(function(){
 var password="";
 var numbers =[0,0,0,0,0,0];
 for(var i=0;i<=5;i++){
    numbers[i] = Math.floor((Math.random() * 25) + 65);
    password += String.fromCharCode(numbers[i]);
 }
   $(".LoginError").text("Nowe haslo: " + password);

  $.ajax({
                    type: 'post',
                    url: 'dzialaj.php',
                    data: {'password': password},
                    cache:false,
                    success: function(data)
                    {
                        alert(data);
                         console.log(result)
        console.log(result.status);
                    }
                });

});
Run Code Online (Sandbox Code Playgroud)

PHP:

if(isset($_POST['password'])){
$temp = $_POST['password'];
echo $temp;
}
Run Code Online (Sandbox Code Playgroud)

Cly*_*yff 6

既然您似乎是 ajax 的新手,让我们尝试一些更简单的事情好吗?检查这个js

<script>
var string = "my string"; // What i want to pass to php

 $.ajax({
    type: 'post', // the method (could be GET btw)
    url: 'output.php', // The file where my php code is
    data: {
        'test': string // all variables i want to pass. In this case, only one.
    },
    success: function(data) { // in case of success get the output, i named data
        alert(data); // do something with the output, like an alert
    }
});
</script>
Run Code Online (Sandbox Code Playgroud)

现在我的output.php

<?php

if(isset($_POST['test'])) { //if i have this post
    echo $_POST['test']; // print it
}
Run Code Online (Sandbox Code Playgroud)

所以基本上我有一个js变量并在我的php代码中使用。如果我需要一个响应,我可以从它那里得到它phpjs像变量一样返回它data

到目前为止一切正常?伟大的。现在js用您当前的代码替换上面提到的。在运行之前,ajax只需执行console.logalert检查您的变量password是否符合您的预期。如果不是,您需要检查您的jshtml代码有什么问题。

这是我认为您要实现的示例(不确定我是否理解正确)

编辑

<script>
var hash = "my hash";

 $.ajax({
    type: 'post',
    url: 'output.php',
    data: {
        'hash': hash        },
    success: function(data) {
        if (data == 'ok') {
            alert('All good. Everything saved!');
        } else {
            alert('something went wrong...');
        } 
    }
});
</script>
Run Code Online (Sandbox Code Playgroud)

现在我的output.php

<?php

if(isset($_POST['hash'])) {
    //run sql query saving what you need in your db and check if the insert/update was successful;
    // im naming my verification $result (a boolean)
    if ($result) echo 'ok';
    else echo 'error';
}
Run Code Online (Sandbox Code Playgroud)

由于页面不会重定向到 php,因此您需要在 ajax 中做出响应以了解 php 代码的结果(如果成功与否)。

这是我在评论中提到的其他答案:

如何使用Javascript通过'POST'方法重定向?

使用 Javascript/jQuery 在重定向时发送 POST 数据?

jQuery - 使用帖子数据重定向

Javascript - 重定向到带有 POST 数据的页面