通过 ajax 将 Javascript 变量传递给 PHP [英] Pass Javascript variable to PHP via ajax
问题描述
我试图将一个变量从我的 javascript 代码传递到服务器端 PHP 代码.我知道这必须通过 ajax 调用来完成,我相信我已经正确完成了,但是当我遇到麻烦时,因为我是 php 新手,访问我从我的 ajax 传递到我的 php 的变量.这是我迄今为止的代码:
I am trying to pass a variable from my javascript code over to the server side PHP code. 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. 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
?>
我正在尝试将我的 javascript 变量userID"传递给 php ($userID),但是我在路上的某个地方出错了.感谢您的帮助!
I'm trying to pass my javascript variable "userID" to php ($userID), however i've gone wrong somewhere along the road. Thanks for the help!
推荐答案
将这样的数据传给ajax调用(http://api.jquery.com/jQuery.ajax/):
Pass the data like this to the ajax call (http://api.jquery.com/jQuery.ajax/):
data: { userID : userID }
并在您的 PHP 中执行此操作:
And in your PHP do this:
if(isset($_POST['userID']))
{
$uid = $_POST['userID'];
// Do whatever you want with the $uid
}
isset()
函数的目的是检查给定的变量是否存在,而不是获取它的值.
isset()
function's purpose is to check wheter the given variable exists, not to get its value.
这篇关于通过 ajax 将 Javascript 变量传递给 PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!