在.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']);
?>
经过大量研究并咨询了我的一位朋友,我得到了答案:如果我们想在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);
?>
希望这可以帮助其他人
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句