在.js中我想使用ajax在json中发送一些多数据。我有问题在我的php中接收它们
JS:
$("#mybtn").on('click'.function(){
$.ajax({
type:'POST',
url: 'handler.php',
data: JSON.stringify({taskId:2 , infos:"blahblah"}),
headers:{
'content-type':'application/json'
},
success: function(response){alert "response";},
error: function(){alert "error";}
});
});
例如,如果taskid为1,我怎样才能在debug.txt中写入信息?
handler.php:
<?php
$temp = $_POST; //also i put $_REQUEST not usefull
file_put_contents('D:\debug.txt',$temp);
//$temp2 = data I don't know how to do it!
if($temp2['taskId']==1){
file_put_contents('D:\debug.txt',$temp2['infos']);
?>
答案 0 :(得分:0)
$.ajax({
type: 'POST',
url: 'destination.php',
data: JSON.stringify({
id: 1,
name: 'user'
}),
headers:{'content-type': 'application/json'},
success: function(response){
//assume we have received data from php in json form:
response = JSON.parse(response);
dosomething(response);
},
error: function(){ alert("Error in Ajaxing"); }
});
现在在php:
<? php
$json = file_get_contents('php://input');
$ary = json_decode($json);
$result = dothings($ary);
$result = json_encode($result);
echo(result);
?>
希望这有助于其他人!
答案 1 :(得分:-1)
Json用PHP编写你的帖子:
$.ajax({
type:'POST',
url: 'handler.php',
data: {taskId:2 , infos:"blahblah"},
success: function(response){alert "response";},
error: function(){alert "error";}
});
并且:
$temp = $_POST;
file_put_contents('D:\debug.txt', json_encode($temp));
if($temp['taskId']==1){
file_put_contents('D:\debug.txt',$temp['infos']);