Javascript PHP没有';无法获取AJAX JSON数据
试图从ajax中获取json数组,但当我试图将其写在文本文件中时,它没有显示任何内容Javascript PHP没有';无法获取AJAX JSON数据,javascript,php,jquery,json,ajax,Javascript,Php,Jquery,Json,Ajax,试图从ajax中获取json数组,但当我试图将其写在文本文件中时,它没有显示任何内容 var img = JSON.parse(localStorage.getItem("iPath")); var img = JSON.stringify(img); console.log(img); $.ajax({ url: './php/temporary.php?
var img = JSON.parse(localStorage.getItem("iPath"));
var img = JSON.stringify(img);
console.log(img);
$.ajax({
url: './php/temporary.php?deletefile',
cache: false,
type: 'POST',
data: img,
success: function( respond, textStatus, jqXHR ){
if( typeof respond.error === 'undefined' ){
//window.location.assign("/buyplace.html");
}
else{
console.log('ОШИБКИ ОТВЕТА сервера: ' + respond.error );
}
},
error: function( jqXHR, textStatus, errorThrown ){
console.log('ОШИБКИ AJAX запроса: ' + textStatus );
}
});
if( isset( $_GET['deletefile'] ) ){
$params = json_decode( $_POST);
$myfile = fopen("testfile.txt", "w");
fwrite($myfile, $params);
//$img = "uploads/" . $imgPath;
//move_uploaded_file($imgPath, "./uploads/");
//unlink('./uploads/' . $img);
}
?>
如何解决此问题?
$\u POST
将包含键值对,您发送的是字符串
因此,您应该阅读标准输入,或者需要确保您实际发送的是键值对
第一个案例已经由@Scuzzy以评论的形式发布
对于后者,使用$\u POST
中的标准键值对:
$.ajax({
url: './php/temporary.php?deletefile',
cache: false,
type: 'POST',
data: {json: img},
// the rest of your js
在php中:
if( isset( $_GET['deletefile'] ) ){
$params = json_decode($_POST['json']);
// the rest of your php
不需要将参数作为JSON发送。您可以使用对象作为
数据:
选项,每个属性将作为相应的$\u POST
元素发送
var img = JSON.parse(localStorage.getItem("iPath"));
console.log(img);
$.ajax({
url: './php/temporary.php?deletefile',
cache: false,
type: 'POST',
data: img,
success: function( respond, textStatus, jqXHR ){
if( typeof respond.error === 'undefined' ){
//window.location.assign("/buyplace.html");
}
else{
console.log('ОШИБКИ ОТВЕТА сервера: ' + respond.error );
}
},
error: function( jqXHR, textStatus, errorThrown ){
console.log('ОШИБКИ AJAX запроса: ' + textStatus );
}
});
在PHP中,需要使用json\u encode()
将$\u POST
数组转换为可以写入文件的字符串
if( isset( $_GET['deletefile'] ) ){
$params = $_POST;
$myfile = fopen("testfile.txt", "w");
fwrite($myfile, json_encode($params));
}
在ajax调用中,它是POST类型,php正在寻找得到它的方法,将php更改为if(isset($\u POST[''deletefile]){}。另外,ajax调用中的deletefile将为空且未设置。请尝试更改.php?deletefile=true您可能需要使用
$jsondata=json\u decode(file\u get\u contents('php://input)
嗯$\u GET['deletefile']
位于URL行上,因此仍应填充它。$\u GET['deletefile']
可以,未正确访问的是数据。img
包含什么?数据中仍然没有任何内容file@VitoMotorsport在调用javascript和php编写文件之间应该会发生很多事情。你需要缩小这个问题的范围。