Javascript 如何使用Ajax发送JSON中的多数据,以及如何在php中接收数据?
在.js中,我想使用ajax发送json中的多数据。我在php中接收它们时遇到问题 js: 例如,如果taskid为1,如何在debug.txt中编写信息 handler.php:Javascript 如何使用Ajax发送JSON中的多数据,以及如何在php中接收数据?,javascript,php,jquery,ajax,json,Javascript,Php,Jquery,Ajax,Json,在.js中,我想使用ajax发送json中的多数据。我在php中接收它们时遇到问题 js: 例如,如果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!
<?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']);
?>
Json用PHP对您的帖子进行编码:
$.ajax({
type:'POST',
url: 'handler.php',
data: {taskId:2 , infos:"blahblah"},
success: function(response){alert "response";},
error: function(){alert "error";}
});
以及:
经过大量研究和咨询我的一位朋友后,我得到了答案: 如果我们想在json中使用ajax发送数据,我们的js应该如下所示:
$.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);
?>
希望这能帮助别人 什么是打印@AbraCadaver:它返回:Array@Barmar请回答这个问题!这没用,它给了我一个空数组:[]@vincent你怎么看这段代码?
$.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
$json = file_get_contents('php://input');
$ary = json_decode($json);
$result = dothings($ary);
$result = json_encode($result);
echo(result);
?>