我想将一些json格式的数据发送到php,并在php中执行一些操作.我的问题是我无法通过ajax将json数据发送到我的php文件.请帮帮我怎么做.我试过这种方法..

<script>
$(function (){
 $("#add-cart").click(function(){
    var bid=$('#bid').val();
    var myqty=new Array()
    var myprice=new Array()

    qty1=$('#qty10').val();
    qty2=$('#qty11').val();
    qty3=$('#qty12').val();

    price1=$('#price1').val();
    price2=$('#price2').val();
    price3=$('#price3').val();

    var postData = 
                {
                    "bid":bid,
                    "location1":"1","quantity1":qty1,"price1":price1,
                    "location2":"2","quantity2":qty2,"price2":price2,
                    "location3":"3","quantity3":qty3,"price3":price3
                }
    var dataString = JSON.stringify(postData);

    $.ajax({
            type: "POST",
            dataType: "json",
            url: "add_cart.php",
            data: {myData:dataString},
            contentType: "application/json; charset=utf-8",
            success: function(data){
                alert('Items added');
            },
            error: function(e){
                console.log(e.message);
            }
    });
});
});
</script>

在PHP中,我使用:

if(isset($_POST['myData'])){
 $obj = json_decode($_POST['myData']);
 //some php operation
}

When in add print_r($_POST) in php file, it shows array(0) {} in firebug.

推荐答案

Lose the contentType: "application/json; charset=utf-8",. You're not sending JSON to the server, you're sending a normal POST query (that happens to contain a JSON string).

That should make what you have work.

Thing is, you don't need to use JSON.stringify or json_decode here at all. Just do:

data: {myData:postData},

然后在PHP中:

$obj = $_POST['myData'];

Json相关问答推荐

如何将自定义卡保存到dart/flutter中的共享偏好设置?

如何使用ChoETL将复杂的JSON转换为CSV

Jolt需要将缺少的值设置为空并保持相同的位置

在PowerShell中,如何获取数据对所在的JSON对象的名称

使用Jolt v.0.1.1向每个json元素添加一个键-值对

JQ-JSON将键转换为对象

重构JOLT代码以获得预期输出

在linux控制台中解析json字符串的最简单方法是什么?

如何使用jolt将嵌套数据变成线性数据

如何在 Apache NiFi 中使用 JoltTransformJson 删除流文件或具有空字段的整个对象?

如何 Select 一个值,这是可选的 - 使用 jq

jq搜索特定字符串并输出对应的父值

TSQL FOR JSON 嵌套值

避免 KeyError 的默认字典键

如何在golang中获取 struct 的json字段名称?

在 Jersey 服务中使用 JSON 对象

使用 jq 如何用其他名称替换键的名称

在 JSON.NET 中序列化派生类时的字段顺序

在android中使用GSON解析带有动态key和value的JSON

从调试器获取 IntelliJ Idea 中的 JSON 对象