代码之家  ›  专栏  ›  技术社区  ›  Alex Mcp

如何使用JSONP下载客户端javascript对象?

  •  2
  • Alex Mcp  · 技术社区  · 14 年前

    1. 在客户端使用该对象,并最终有一个“下载我”链接
    2. application/json

    现在这是我的作品:

    服务器端代码

    <?php
    $data = array('zero', 'one', 'two', 'testing the encoding');  
    $json = json_encode($data);  
    //$json = json_encode($_GET['']); //eventually I'll encode their data, but I'm testing
    header("Content-type: application/json"); 
    header('Content-Disposition: attachment; filename="backup.json"'); 
    echo $_GET['callback'] . ' (' . $json . ');';
    ?>
    

    $("#download").click(function(){
        var json = JSON.stringify(collection); //serializes their object
        $.ajax({
           type: "GET",
           url: "http://www.myURL.com/api.php?callback=?", //this is the above script
           dataType: "jsonp",
           contentType: 'jsonp',
           data: json,
           success: function(data){
               console.log( "Data Received: " + data[3] );
           }
        });
        return false;
    });
    

    现在当我参观 api.php download.json

     (["zero","one","two","testing the encoding"]);
    

    当我点击 #download 要运行AJAX调用,它需要登录Firebug

    Data Received: testing the encoding
    

    这几乎是我所期望的。我正在接收JSON字符串并序列化它,这很好。我错过了两件事:

    1. 当我在浏览器中访问页面时,我需要做什么才能获得相同的下载行为提示
    1 回复  |  直到 14 年前
        1
  •  2
  •   Ignacio Vazquez-Abrams    14 年前
    1. window.location .
    2. 因为它是一个字符串,所以它将作为原始查询字符串的一部分发送。试试看里面 $_SERVER['QUERY_STRING']