$(function(){$.ajax({ url:'check.php', //api介面地址 data:{ "head": { "name": "test", }, "body": { "age ": "2", } }, type:'post', //資料轉送方式 dataType:'json',//資料轉送格式 cache:false, success:function(data) { //執行成功後的回呼函數,data為返回的資料 alert(data); }, error : function() { alert('error'); }});});
新手,求問為什麼這個老是顯示error,也就是說post不成功?怎麼改?後台接收的話用PHP怎麼解析這個資料呢?
回複內容:
$(function(){$.ajax({ url:'check.php', //api介面地址 data:{ "head": { "name": "test", }, "body": { "age ": "2", } }, type:'post', //資料轉送方式 dataType:'json',//資料轉送格式 cache:false, success:function(data) { //執行成功後的回呼函數,data為返回的資料 alert(data); }, error : function() { alert('error'); }});});
新手,求問為什麼這個老是顯示error,也就是說post不成功?怎麼改?後台接收的話用PHP怎麼解析這個資料呢?
將Json作為字串進行編碼,然後以一個參數傳送到後台,在後台進行解碼在解析json;
var json={ "head": { "name": "test", }, "body": { "age ": "2", } };var str=JSON.stringify(json);$(function(){$.ajax({ url:'check.php', //api介面地址 data:{json:escape(str)}, type:'post', //資料轉送方式 dataType:'json',//資料轉送格式 cache:false, success:function(data) { //執行成功後的回呼函數,data為返回的資料 alert(data); }, error : function() { alert('error'); }});});
這樣就把複雜Json對象作為一個參數傳遞到後台。
php後台接收:POST["json"]的值,然後解碼解析;
json格式錯誤,"test", "2" 後面都不需要 逗號
做json encode轉換為字串形式,php那邊json_decode一下就行了,比如
data:{values: $.jsonEncode({header:...})} //js端怎麼jsonencode我忘了,自己查一下哈。
然後
$parameters = json_decode($_POST['values']);
後台接收的話用PHP:json_decode(file_get_contents('php://input'), true);
首先 errror 是你的伺服器沒有返回 JSON 格式的資料,
然後"head","body"後面應該跟字串吧,
最後在PHP端,可以 $_POST['head'] , $_POST['body']擷取 head,body的字串
age
後面有空格嗎?記得type
應該是POST吧,還有dataType
你看下有問題沒
$(function(){$.ajax({ url:'check.php', //api介面地址 data:{ "head": { "name": "test", }, "body": { "age": "2", } }, type:'POST', //資料轉送方式 dataType:'application/json',//資料轉送格式 cache:false, success:function(data) { //執行成功後的回呼函數,data為返回的資料 alert(data); }, error: function() { alert('error'); }});});
格式錯誤了,'test'和'2'後面的逗號都要去掉,你試下