2

我正在尝试将客户端 javascript 对象保存为本地文件。我不确定这是否可能。

基本架构是这样的:

  1. Ping 外部 API 以取回 JSON 对象
  2. 使用该对象在客户端工作,并最终获得“下载我”链接
  3. 此链接将数据发送到我的服务器,该服务器对其进行处理并使用 mime type 将其发送回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使用 Firefox 访问该站点时,它会提示下载download.json并生成此文本文件,如预期的那样:

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

当我单击#download运行 AJAX 调用时,它会登录 Firebug

Data Received: testing the encoding

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

实际问题

  1. 我需要做什么才能获得与在浏览器中访问页面时相同的提示下载行为
  2. (更简单)我如何在服务器端访问发送到服务器的 json 对象以对其进行序列化?我不知道它在 GET 数组中的索引是什么(很傻,我知道,但我几乎尝试了所有方法)
4

1 回答 1

2
  1. 您需要告诉浏览器访问该页面,通常通过设置window.location.
  2. 由于它是一个字符串,它将作为原始查询字符串的一部分发送。尝试寻找$_SERVER['QUERY_STRING']它。
于 2010-03-14T02:14:02.913 回答