发送JSON使用Ajax的PHP [英] Sending JSON to PHP using ajax

查看:165
本文介绍了发送JSON使用Ajax的PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要JSON格式的一些数据发送到PHP和做一些操作在PHP。我的问题是无法通过AJAX发送JSON数据给我的PHP file.Please帮助我,我怎么能做到这一点。我曾尝试这种方式。

I want to send some data in json format to php and do some operation in php. My problem is i can't send json data via ajax to my php file.Please help me how can i do that. I have tried this way..

<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
}

当在加的print_r($ _ POST)的PHP文件,它显示了阵列(0){}中的萤火虫。

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

推荐答案

失去的contentType:应用/ JSON的;字符集= UTF-8,。你不是JSON发送到服务器,你发送一个正常的POST查询(即恰好包含一个JSON字符串)。

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.

事情是,你并不需要使用 JSON.stringify json_de code 在这里所有。只要做到:

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

data: {myData:postData},

然后在PHP中:

Then in PHP:

$obj = $_POST['myData'];

这篇关于发送JSON使用Ajax的PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆