简体   繁体   English

PHP的AJAX返回变量

[英]AJAX return variable from PHP

When a user clicks download it will successfully create a zip on server with the files, then it should alert the the zips location (variable $zip) from php as a response but instead it is alerting [object Object]. 当用户单击下载时,它将成功在服务器上创建包含文件的zip,然后它应从php警报zip位置(变量$ zip)作为响应,但它会向[object Object]发出警报。 Everything else is working how it should. 其他一切都按预期进行。 What am I doing wrong? 我究竟做错了什么?

JQuery: JQuery的:

$('.download').click(function() { 
window.keys = [];
$('.pad').each(function(i, obj) {
    var key = $(this).attr('key');
        keys.push(key)
});
var jsonString = JSON.stringify(keys);
$.ajax({
      type:'post',
    url:'download.php',
    data: {data : jsonString}, 
        cache: false,
   dataType: 'json',
    success: function(data){

       alert(data);

      }
 });
});

PHP: PHP:

<?php


$data = json_decode(stripslashes($_POST['data']));

$numbercode = md5(microtime());
$zip = new ZipArchive();
$zip->open('kits/'.$numbercode.'.zip', ZipArchive::CREATE);

foreach($data as $d) {

$zip->addFile($d);  

}

$zip->close();



echo json_encode($zip);
?>

The return type is a JavaScript object, which will result in what you see. 返回类型是一个JavaScript对象,它将产生您所看到的内容。

First, you should console.log(data) , to get the structure. 首先,您应该console.log(data) ,以获取结构。 You can also do this by looking at the Network Tab in Chrome. 您也可以通过查看Chrome中的“网络”标签来执行此操作。

After you know the structure of data , you can use the value. 知道data的结构后,就可以使用该值。

For example, then alert(data.location) , to alert the actual value. 例如,然后alert(data.location)来警告实际值。

remove your dataType from the ajax, it alert [Object Object] because your result becomes json object if you specify dataType: 'json', , 从ajax中删除dataType ,它会警告[Object Object],因为如果您指定dataType: 'json',

and in php- 和在PHP-

// to echo the location of the zipfile
echo 'kits/'.$numbercode.'.zip';

Thanks to @jake2389 I see what I was doing wrong, I basically just had to create a new variable within PHP which I called $link with the data I wanted to send back to AJAX because $zip was defined as a zip archive not a string. 多亏@ jake2389,我才知道我在做什么错,我基本上只需要在PHP中创建一个新变量,我将其想要发送回AJAX的数据称为$ link,因为$ zip被定义为zip归档文件而不是字符串。 。 Here is what I changed and now it is working. 这是我更改的内容,现在可以正常工作了。

PHP: PHP:

<?php


$data = json_decode(stripslashes($_POST['data']));

$numbercode = md5(microtime());
$zip = new ZipArchive();
$zip->open('kits/'.$numbercode.'.zip', ZipArchive::CREATE);

foreach($data as $d) {

$zip->addFile($d);  

}

$zip->close();

$link = 'kits/'.$numbercode.'.zip';

echo json_encode($link);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM