【问题标题】:Failing to send to $_POST but $_SESSION says something else未能发送到 $_POST 但 $_SESSION 说了别的
【发布时间】:2016-10-11 20:28:33
【问题描述】:

我不知道我的代码发生了什么,当我运行它时,有时 SESSION 说存储了一个数组,有时却没有。我正在使用调试器来检查会话。当我使用 isset($_POST) 时,返回值始终为 false。我正在使用 ajax 将数组传递给 php。

<?php
session_start();
if(isset($_POST['jExam'])){
    $decode = json_decode($_POST['jExam']);
    $_SESSION['receive'] = $decode;
    $product = $_SESSION['receive'];
}
else{
    echo "Failed to hold<br>";
}
?>

Javascript:

$(document).ready(function(){
    $(".class").click(function(event)){
    event.preventDefault();
    window.location.href = 'example.php';
    var jExample = JSON.stringify(array);
    $.ajax({
        data:{'jExam':jExample},
        type: 'POST',
        dataType: 'json',
        url: 'example.php'
    });
});

编辑:

弄清楚为什么将数组存储到SESSION中,一旦我单击打开另一个页面的按钮,然后在url中输入之前的页面,数组就会存储到SESSION中。不知道为什么。仍然无法弄清楚为什么 ajax 不发送到帖子。

编辑 2:

我创建了一个处理请求的文件,称为handle.php。所以顶部的php脚本被添加到handle.php而不是网页中。但我收到“解析错误:语法错误,意外'if'(T_IF)”。上面的代码还是一样的。

handle.php:

<?php
    session_start();
    if(isset($_POST['jExam'])){
        $decode = json_decode($_POST['jExam']);
        $_SESSION['receive'] = $decode;
        $product = $_SESSION['receive'];
    }
    else{
        echo "Failed to hold<br>";
    }
?>

编辑 3:

我正在使用 ajax 将数组传递给 php,以便将其存储到会话中,以便在另一个页面中使用该数组。问题是数组没有传递到 $_POST。我希望该数组实际上可以通过,以便我可以在另一个页面上使用它。

已解决:

我所做的只是添加一个具有隐藏值的表单。而实际发布的价值

<form id = "postform" action = "cart.php" method = "post">
  <input type = "hidden" id="obj" name="obj" val="">
  <input type = "submit" value = "Show Cart" id = "showcart">
</form>

在 Javascript 中:

$(document).ready(function(){
  $("#showcart").click(function(){
    var json = JSON.stringify(object)
    $('#obj').val(json);
    $('#obj').submit();
  });
});

感谢大家的回答,但希望这对其他人有所帮助。

【问题讨论】:

  • 这个问题可能是你的JS引起的。你有没有尝试在 vanilla JS 中做到这一点?
  • 最好使用 print_r($_POST);在会话开始行之后。并分享结果。另请注意,要检查会话值,您必须刷新页面。
  • example.php 是当前站点,还是处理请求的 php-File?
  • example.php 是另一个页面,我应该创建一个处理请求的 php 文件吗?
  • 好的,我添加了一个处理请求的php_File,仍然失败

标签: javascript php ajax session post


【解决方案1】:

如果exam​​ple.php是处理请求的php文件,你需要把你的js代码改成

$(document).ready(function(){
    $(".class").click(function(event)){
    event.preventDefault();
    var jExample = JSON.stringify(array);

    $.ajax("example.php", {
        data:{'jExam':jExample},
        type: 'POST',
        dataType: 'json'
    });
});

如果你想处理响应,你应该添加完整参数。

您的错误是,您甚至在发送请求之前就使用window.location.href 重定向了页面。因此,您的请求永远不会被发送,而是直接调用 PHP 文件,而不是通过 AJAX,而不是使用必要的数据。因此,您缺少 PHP 文件中的数据。

【讨论】:

  • @charlietfl 我这样做了,这就是我读到的there。纠正我,如果我仍然错了,但我不相信。
  • @charlietfl 哦,你说得对,我搞砸了。谢谢你纠正我。
  • 它也需要是一个字符串
  • @charlietfl 哎呀,谢谢你。不知道,我怎么错过了。
  • @Syntac no js不在php文件中,我为js做了一个单独的文件
【解决方案2】:

您会想尝试让这个设置对自己来说更容易一些,所以这里有一些可以帮助您简化它的事情。您可能已经完成了其中的一些操作,也可能没有完成,因此请忽略您已经完成的任何操作:

  1. 使用包含在 1 级 php 文件中的具体定义的配置文件
  2. 只需将data 字段传递给json_encode()
  3. 不要将json作为数据类型发送,不是必须的,先排查问题,如果需要,将其设为默认发送类型
  4. 使用success 函数,以便您可以轻松查看返回
  5. 创建功能以分隔任务

/config.php

添加所有重要的首选项并将其添加到每个顶级页面。

session_start();
define('URL_BASE','http://www.example.com');
define('URL_AJAX',URL_BASE.'/ajax/dispatch.php');
define('FUNCTIONS',__DIR__.'/functions');

表格:

只需创建一个data,它将发送一组数据键/值。

<button class="cart" data-instructions='<?php echo json_encode(array('name'=>'Whatever','price'=>'17.00','action'=>'add_to_cart')); ?>'>Add to Cart</button>

给你:

<button class="cart" data-instructions='{"name":"Whatever","price":"17.00","action":"add_to_cart"}'>Add to Cart</button>

阿贾克斯:

只需发送一个普通对象

$(document).ready(function(){
    // Doing it this way allows for easier access to dynamic
    // clickable content
    $(this).on('click','.cart',function(e)){
        e.preventDefault();
        // Get just the one data field with all the data
        var data = $(this).data('instructions');
        $.ajax({
            data: data,
            type: 'POST',
            // Use our defined constant for consistency
            // Writes: http://www.example.com/ajax/dispatch.php
            url: '<?php echo URL_AJAX; ?>',
            success: function(response) {
                // Check the console to make sure it's what we expected
                console.log(response);
                // Parse the return
                var dataResp = JSON.parse(response);
                // If there is a fail, show error 
                if(!dataResp.success)
                    alert('Error:'+dataResp.message);
            }
        });
    });
});

/functions/addProduct.php

理想情况下,您希望使用某种IDsku 作为键,而不是名称

// You will want to pass a sku or id here as well
function addProduct($name,$price)
    {
        $_SESSION['cart'][$name]['name']  = $name;
        $_SESSION['cart'][$name]['price'] = $price;

        if(isset($_SESSION['cart'][$name]['qty']))
            $_SESSION['cart'][$name]['qty'] += 1;
        else
            $_SESSION['cart'][$name]['qty'] = 1;

        return $_SESSION['cart'][$name];
    }

/ajax/dispatcher.php

调度程序仅作为 AJAX 请求回调操作。由于返回机制的性质,您可以将其扩展为返回 html,或连续运行多个命令,或仅运行一个,或其他任何命令。

# Add our config file so we have access to consistent prefs
# Remember that the config has session_start() in it, so no need to add that
require_once(realpath(__DIR__.'/../..').'/config.php');
# Set fail as default
$errors['message'] = 'Unknown error';
$errors['success'] = false;
# Since all this page does is receive ajax dispatches, action
# should always be required
if(!isset($_POST['action'])) {
    $errors['message'] = 'Action is require. Invalid request.';
    # Just stop
    die(json_encode($errors));
}
# You can have a series of actions to dispatch here.
switch($_POST['action']) {
    case('add_to_cart'):
        # Include function and execute it
        require_once(FUNCTIONS.'/addProduct.php');
        # You can send back the data for confirmation or whatever...
        $errors['data']    = addProduct($_POST['name'],$_POST['price']);
        $errors['success'] = true;
        $errors['message'] = 'Item added';
        # Stop here unless you want more actions to run
        die(json_encode($errors));
    //You can add more instructions here as cases if you wanted to...
    default:
        die(json_encode($errors));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    相关资源
    最近更新 更多