2
我想將客戶端JavaScript對象保存爲本地文件。我不確定這是否可能。如何使用JSONP下載客戶端JavaScript對象?
的基本架構是這樣的:
- 平安外部API取回一個JSON對象
- 工作的客戶端與該對象,並最終有一個「下載我」鏈接
- 這鏈接將數據發送到我的服務器,該服務器對其進行處理並將其發送回MIME類型
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字符串並將其序列化,這非常棒。我失去了兩件事情:
的實際問題
- 我需要什麼,當我訪問該頁面在瀏覽器中 做才能得到相同的提示到下載行爲,我得到
- (更簡單)如何訪問服務器端的json對象被髮送到服務器來序列化它?我不知道它是GET數組中的什麼指數(傻了,我知道,但我已經試過幾乎所有的東西)