阿贾克斯没有通过$ _POST

时间:2016-10-09 07:44:03

标签: javascript php ajax

麻烦将ajax传递给$_POST,它总是返回false。

到目前为止我尝试过的内容:

  • 使用contentType:'application/json; charset=UTF-8'
  • 为ajax创建函数并添加到jQuery onclick
  • 在Javascript中移除了dataType,console.log: Object {readyState: 0, responseText: "", status: 0, statusText: "error"}
  • 使用Javascript中的dataType Object {readyState: 4, responseText: "↵ ↵Failed to hold<br>", status: 200, statusText: "OK"}

使用Javascript:

        $(document).ready(function(){
            $("#showcart").click(function(event){
                event.preventDefault();
                $.ajax({
                    data: {'jCart':JSON.stringify(cart)},
                    type: 'POST',
                    dataType: 'json',   
                    url: 'storecart.php',
                    contentType:'application/json; charset=UTF-8',
                    success: function(data){
                        console.log("Success")
                    },
                    error: errorFunction
                });

            }); 
        });

function errorFunction(){
    console.log("Error");
}

Storecart.php

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

Cart.php

<?php 
    session_store();
    include(Storecart.php);
?>

在控制台上,它会说"Error"

在cart.PHP上,它会显示"Failed to hold"

我所知道的是ajax运行不正常,我不知道如何修复它。

ajax的ALMOST解决方案,但由于某种原因无法发布

不知道为什么,但它对我有用。

创建一个函数:

function showcart(){
    var jData = JSON.stringify(cart);
    $.ajax({
        url:"storecart.php",
        type:"post",
        data: 'datastring=' + jData,
        datatype: "json",
        success: function(data){
            console.log("SUCCESS")
            console.log(jData);
        },
        error: function(data){
            console.log("REDO")
        }
    });     
}

将其添加到javascript:

 $(document).ready(function(){
    $("#showcart").click(function(event){
        event.preventDefault();
        showcart();
        }); 
    });

2 个答案:

答案 0 :(得分:0)

您没有在发送数据的任何地方声明购物车 数据:{&#39; jCart&#39;:JSON.stringify(cart)}

答案 1 :(得分:0)

尝试更改您的代码:

        var dataJcart = {
         "var": "example jcart"
        };
        var dataString = JSON.stringify(dataJcart);

          $(document).ready(function(){
            $("#showcart").click(function(event){
            event.preventDefault();
            $.ajax({
                url: 'storecart.php',
                type: 'POST',
                data:{'jCart': dataString},
                success: function(data){
                    console.log(data);
                },
                error: errorFunction
            });

        }); 
    });
    function errorFunction(){
     console.log("Error non");
 }

Storecart.php

   if(isset($_POST["jCart"]))
    {
        $decode = json_decode($_POST["jCart"]);
        echo $decode->var;
    }
相关问题