douqiao8032
2017-02-20 03:38 阅读 137

AJAX从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]. Everything else is working how it should. What am I doing wrong?

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


$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);
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    dpwh11290 dpwh11290 2017-02-20 03:41

    The return type is a JavaScript object, which will result in what you see.

    First, you should console.log(data), to get the structure. You can also do this by looking at the Network Tab in Chrome.

    After you know the structure of data, you can use the value.

    For example, then alert(data.location), to alert the actual value.

    点赞 7 评论 复制链接分享
  • douzhi7070 douzhi7070 2017-02-20 03:42

    remove your dataType from the ajax, it alert [Object Object] because your result becomes json object if you specify dataType: 'json',,

    and in php-

    // to echo the location of the zipfile
    echo 'kits/'.$numbercode.'.zip';
    
    点赞 3 评论 复制链接分享
  • dongshuofu0039 dongshuofu0039 2017-02-20 03:44

    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. Here is what I changed and now it is working.

    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);
    ?>
    
    点赞 评论 复制链接分享

相关推荐