【问题标题】:Pass integer from jQuery to PHP Session array将整数从 jQuery 传递到 PHP 会话数组
【发布时间】:2017-08-09 21:35:42
【问题描述】:

我正在尝试将一个整数从 jQuery 传递到 PHP 中的 Session 数组。 我有一个带有 id 的按钮,这个 id 应该添加到会话数组中。

我开始会话:

// 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']);?>

我哪里出错了? 谢谢!

【问题讨论】:

  • 我认为您应该编辑您的帖子以提供更多信息 - 例如:这段代码的结果是什么?您是否在控制台中看到“Yay it works”消息或“出现问题”?阵列是否已填充?还有,ajaxurl是什么,想必你确定要回发到PHP页面吧?
  • @DaveyDaveDave 当我运行该函数时,我得到“出了点问题”。 ajaxurl 是一个 jquery var,其中包含 php 文件的 url,该文件包含我原始帖子中的 php。

标签: php jquery session


【解决方案1】:

您没有为 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中,使用$_POST['id']来访问参数。

<?php
session_start();
array_push($_SESSION['parts'],$_POST['id']);
print_r($_SESSION['parts']);
?>

另外,print_r() 不会产生JSONP 格式输出,所以不要使用dataType: 'jsonp'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多