简体   繁体   English

通过ajax将Javascript变量传递给PHP

[英]Pass Javascript variable to PHP via ajax

I am trying to pass a variable from my javascript code over to the server side PHP code.我试图将一个变量从我的 javascript 代码传递到服务器端 PHP 代码。 I know this must be done via an ajax call which i believe i have done correctly, however accessing the variable i pass from my ajax into my php is when i run into trouble as i am new to php.我知道这必须通过 ajax 调用来完成,我相信我已经正确完成了,但是当我遇到麻烦时,因为我是 php 新手,访问我从我的 ajax 传递到我的 php 的变量。 Here is my code i have thus far:这是我迄今为止的代码:

$(document).ready(function() {

            $(".clickable").click(function() {
                var userID = $(this).attr('id');
                //alert($(this).attr('id'));
                $.ajax({
                    type: "POST",
                    url: 'logtime.php',
                    data: "userID=" + userID,
                    success: function(data)
                    {
                        alert("success!");
                    }
                });
            });
        });

<?php //logtime.php
$uid = isset($_POST['userID']);
//rest of code that uses $uid
?>

I'm trying to pass my javascript variable "userID" to php ($userID), however i've gone wrong somewhere along the road.我试图将我的 javascript 变量“userID”传递给 php ($userID),但是我在路上的某个地方出错了。 Thanks for the help!谢谢您的帮助!

Pass the data like this to the ajax call ( http://api.jquery.com/jQuery.ajax/ ):将这样的数据传递给 ajax 调用( http://api.jquery.com/jQuery.ajax/ ):

data: { userID : userID }

And in your PHP do this:在你的 PHP 中这样做:

if(isset($_POST['userID']))
{
    $uid = $_POST['userID'];

    // Do whatever you want with the $uid
}

isset() function's purpose is to check wheter the given variable exists, not to get its value. isset()函数的目的是检查给定变量是否存在,而不是获取其值。

Since you're not using JSON as the data type no your AJAX call, I would assume that you can't access the value because the PHP you gave will only ever be true or false.由于您没有使用 JSON 作为数据类型,也没有使用 AJAX 调用,因此我假设您无法访问该值,因为您提供的 PHP 只会是真或假。 isset is a function to check if something exists and has a value, not to get access to the value. isset是一个函数,用于检查某物是否存在并具有值,而不是访问该值。

Change your PHP to be:将您的 PHP 更改为:

$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 0;

The above line will check to see if the post variable exists.上面的行将检查 post 变量是否存在。 If it does exist it will set $uid to equal the posted value.如果它确实存在,它会将$uid设置$uid等于发布的值。 If it does not exist then it will set $uid equal to 0.如果它不存在,那么它将设置$uid等于 0。

Later in your code you can check the value of $uid and react accordingly稍后在您的代码中,您可以检查$uid的值并做出相应的反应

if($uid==0) {
    echo 'User ID not found';
}

This will make your code more readable and also follow what I consider to be best practices for handling data in PHP.这将使您的代码更具可读性,并遵循我认为在 PHP 中处理数据的最佳实践。

To test if the POST variable has an element called 'userID' you would be better off using array_key_exists .. which actually tests for the existence of the array key not whether its value has been set .. a subtle and probably only semantic difference, but it does improve readability.要测试 POST 变量是否有一个名为“userID”的元素,您最好使用 array_key_exists .. 它实际上测试数组键的存在,而不是它的值是否已设置.. 一个微妙的,可能只是语义差异,但是它确实提高了可读性。

and right now your $uid is being set to a boolean value depending whether $__POST['userID'] is set or not ... If I recall from memory you might want to try ...现在你的 $uid 被设置为一个布尔值,取决于是否设置了 $__POST['userID'] ......如果我从记忆中回忆起你可能想尝试......

$uid = (array_key_exists('userID', $_POST)?$_POST['userID']:'guest';

Then you can use an identifiable 'guest' user and render your code that much more readable :)然后您可以使用可识别的“访客”用户并使您的代码更具可读性:)

Another point re isset() even though it is unlikely to apply in this scenario, it's worth remembering if you don't want to get caught out later ... an array element can be legitimately set to NULL ... ie it can exist, but be as yet unpopulated, and this could be a valid, acceptable, and testable condition.另一点 reisset() 即使在这种情况下不太可能适用,但如果您不想稍后被发现,那么值得记住...数组元素可以合法地设置为 NULL...即它可以存在,但尚未填充,这可能是有效、可接受和可测试的条件。 but :但 :

a = array('one'=>1, 'two'=>null, 'three'=>3);
isset(a['one']) == true
isset(a['two']) == false

array_key_exists(a['one']) == true
array_key_exists(a['two']) == true

Bw sure you know which function you want to use for which purpose. Bw 确定您知道要用于哪个目的的函数。

Alternatively, try removing "data" and making the URL "logtime.php?userID="+userId或者,尝试删除“数据”并将 URL 设为“logtime.php?userID="+userId

I like Brian's answer better, this answer is just because you're trying to use URL parameter syntax in "data" and I wanted to demonstrate where you can use that syntax correctly.我更喜欢布赖恩的答案,这个答案只是因为您尝试在“数据”中使用 URL 参数语法,我想演示您可以在何处正确使用该语法。

$(document).ready(function() {
            $(".clickable").click(function() {
                var userID = $(this).attr('id'); // you can add here your personal ID
                //alert($(this).attr('id'));
                $.ajax({
                    type: "POST",
                    url: 'logtime.php',
                    data : {
                        action : 'my_action',
                        userID : userID 
                    },
                    success: function(data)
                    {
                        alert("success!");
                        console.log(data);
                    }
                });
            });
        });


 $uid = (isset($_POST['userID'])) ? $_POST['userID'] : 'ID not found';
 echo $uid;

$uid add in your functions $uid在你的函数中添加

note: if $ is not supperted than add jQuery where $ defined注意:如果$不是 supperted 则在 $ 定义的地方添加jQuery

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

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