使用ajax将JSON发送到PHP
发布时间:2020-12-16 03:08:47 所属栏目:百科 来源:网络整理
导读:我想以json格式将一些数据发送到php并在php中进行一些操作。我的问题是我无法通过ajax将json数据发送到我的php文件。请帮助我,我该怎么做。我试过这种方式.. script$(function (){ $("#add-cart").click(function(){ var bid=$('#bid').val(); var myqty=ne
我想以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){}。
丢失contentType:“application / json; charset = utf-8”,.您没有向服务器发送JSON,而是发送正常的POST查询(恰好包含JSON字符串)。
这应该成为你的工作。 事实是,你根本不需要在这里使用JSON.stringify或json_decode。做就是了: data: {myData:postData}, 然后在PHP中: $obj = $_POST['myData']; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |