将整数从jQuery传递到PHP会话数组
我试图在PHP中将一个整数从jQuery传递到会话数组。 我有一个id为的按钮,这个id应该添加到会话数组中 我以以下内容开始本次会议:将整数从jQuery传递到PHP会话数组,php,jquery,session,Php,Jquery,Session,我试图在PHP中将一个整数从jQuery传递到会话数组。 我有一个id为的按钮,这个id应该添加到会话数组中 我以以下内容开始本次会议: // ADD SESSION START TO HEADER function hook_session() { if(session_id() == ''){ session_start(); $parts=array(); $_SESSION['parts']=$parts; } } add_action('wp
// ADD SESSION START TO HEADER
function hook_session() {
if(session_id() == ''){
session_start();
$parts=array();
$_SESSION['parts']=$parts;
}
}
add_action('wp_head', 'hook_session');
我的jQuery:
$('.product-button').click(function(){
$id = $(this).val();
$id = parseInt($id);
$.ajax({
url: ajaxurl,
type: 'POST',
data: $id,
dataType: 'jsonp',
success: function (result) {
console.log('Yay it worked');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Something went wrong');
}
});
});
我的PHP:
<?php
array_push($_SESSION['parts'],$_POST[$id]);
print_r($_SESSION['parts']);?>
我哪里做错了?
谢谢 您没有为
POST
参数指定名称
$.ajax({
url: ajaxurl,
type: 'POST',
data: { id: $id },
success: function (result) {
console.log('Yay it worked');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Something went wrong');
}
});
<?php
session_start();
array_push($_SESSION['parts'],$_POST['id']);
print_r($_SESSION['parts']);
?>
然后在PHP中,使用$\u POST['id']
访问参数
$.ajax({
url: ajaxurl,
type: 'POST',
data: { id: $id },
success: function (result) {
console.log('Yay it worked');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Something went wrong');
}
});
<?php
session_start();
array_push($_SESSION['parts'],$_POST['id']);
print_r($_SESSION['parts']);
?>
另外,
print\u r()
不会产生JSONP
格式输出,因此不要使用dataType:'JSONP'
您没有给POST
参数命名
$.ajax({
url: ajaxurl,
type: 'POST',
data: { id: $id },
success: function (result) {
console.log('Yay it worked');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Something went wrong');
}
});
<?php
session_start();
array_push($_SESSION['parts'],$_POST['id']);
print_r($_SESSION['parts']);
?>
然后在PHP中,使用$\u POST['id']
访问参数
$.ajax({
url: ajaxurl,
type: 'POST',
data: { id: $id },
success: function (result) {
console.log('Yay it worked');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Something went wrong');
}
});
<?php
session_start();
array_push($_SESSION['parts'],$_POST['id']);
print_r($_SESSION['parts']);
?>
另外,
print\u r()
不会产生JSONP
格式输出,所以不要使用dataType:'JSONP'
我认为你应该编辑你的帖子来提供更多的信息,比如:这段代码的结果是什么?您是否在控制台中看到您的“耶,它工作了”消息或“出了问题”?阵列是否已填充?另外,什么是ajaxurl
,可能您确定您正在发回PHP页面?@daveydaveDaveDave当我运行函数时,我得到“出了问题”。ajaxurl是一个jquery变量,它包含php文件的url,该文件在我的原始文章中包含php。我认为您应该编辑您的文章以提供更多的信息,比如:这段代码的结果是什么?您是否在控制台中看到您的“耶,它工作了”消息或“出了问题”?阵列是否已填充?另外,什么是ajaxurl
,可能您确定您正在发回PHP页面?@daveydaveDaveDave当我运行函数时,我得到“出了问题”。ajaxurl是一个jquery变量,它包含指向php文件的url,该文件包含我的原始帖子中的php。