使用ajax将JSON发送到PHP

时间:2012-06-08 19:32:22

标签: php jquery ajax json

我想以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
}

当在php文件中添加print_r($ _ POST)时,它会在firebug中显示array(0){}。

8 个答案:

答案 0 :(得分:39)

失去contentType: "application/json; charset=utf-8",。您没有向服务器发送JSON,而是发送正常的POST查询(恰好包含JSON字符串)。

这应该使你的工作成功。

事情是,你根本不需要在这里使用JSON.stringifyjson_decode。只是做:

data: {myData:postData},

然后在PHP中:

$obj = $_POST['myData'];

答案 1 :(得分:21)

那是因为$_POST预先填充了表单数据。

要获取JSON数据(或任何原始输入),请使用php://input

$json = json_decode(file_get_contents("php://input"));

答案 2 :(得分:9)

使用json和ajax将javascript obj发送到php:

JS:

var dataPost = {
   "var": "foo"
};
var dataString = JSON.stringify(dataPost);

$.ajax({
   url: 'server.php',
   data: {myData: dataString},
   type: 'POST',
   success: function(response) {
      alert(response);
   }
});

在php中使用该对象:

$obj = json_decode($_POST["myData"]);

echo $obj->var;

答案 3 :(得分:4)

我相信你可以尝试这样的事情:

var postData = 
            {
                "bid":bid,
                "location1":"1","quantity1":qty1,"price1":price1,
                "location2":"2","quantity2":qty2,"price2":price2,
                "location3":"3","quantity3":qty3,"price3":price3
            }
$.ajax({
        type: "POST",
        dataType: "json",
        url: "add_cart.php",
        data: postData,
        success: function(data){
            alert('Items added');
        },
        error: function(e){
            console.log(e.message);
        }
});

json编码应该自动发生,你的帖子的转储应该给你这样的东西:

array(
    "bid"=>bid,
    "location1"=>"1",
    "quantity1"=>qty1,
    "price1"=>price1,
    "location2"=>"2",
    "quantity2"=>qty2,
    "price2"=>price2,
    "location3"=>"3",
    "quantity3"=>qty3,
    "price3"=>price3
)

答案 4 :(得分:3)

如果要通过$_POST变量获取值,则不应将contentType指定为"application/json",而应使用默认的"application/x-www-form-urlencoded; charset=UTF-8":< / p>

JavaScript:

var person = { name: "John" };

$.ajax({
    //contentType: "application/json", // php://input
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: {data: person}
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

// $_POST

$jsonString = $_POST['data'];

$newJsonString = json_encode($jsonString);
header('Content-Type: application/json');
echo $newJsonString;

否则,如果您要将JSON从JavaScript发送到PHP:

JavaScript:

var person = { name: "John" };

$.ajax({
    contentType: "application/json", // php://input
    //contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: person
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

$jsonString = file_get_contents("php://input");
$phpObject = json_decode($jsonString);

$newJsonString = json_encode($phpObject);
header('Content-Type: application/json');
echo $newJsonString;

答案 5 :(得分:2)

只需删除:

...
//dataType: "json",
url: "index.php",
data: {myData:postData},
//contentType: "application/json; charset=utf-8",
...

答案 6 :(得分:1)

您正在尝试使用js对象格式发送js数组。而不是使用

var a = new array();
a['something']=...

尝试:

var a = new Object();
a.something = ...

答案 7 :(得分:0)

我知道它已经有一段时间了,但万一有人还需要它:

我需要传递的JSON对象:

0:{CommunityId: 509, ListingKey: "20281", Type: 10, Name: "", District: "", Description: "",…}
1:{CommunityId: 510, ListingKey: "20281", Type: 10, Name: "", District: "", Description: "",…}

Ajax代码:

data: JSON.stringify(The-data-shows-above),
type: 'POST',
datatype: 'JSON',
contentType: "application/json; charset=utf-8"

PHP方面:

json_decode(file_get_contents("php://input"));

它对我有用,希望它可以帮助!