2011-11-21 73 views
1

我在主腳本這個...JSONP我做對了嗎?

(function(d){ 
    var shortURLjs, id = 'shortUrl'; 
    if (d.getElementById(id)) {return;} 
    shortURLjs = d.createElement('script'); 
    shortURLjs.id = id; 
    shortURLjs.async = true; 
    shortURLjs.src = "http://site.com/test.js"; 
    d.getElementsByTagName('body')[0].appendChild(shortURLjs); 
}(document)); 

而在test.js我有...

shortURL = { "firstName": "John", "lastName" : "Smith"}; 

但是,當我試圖從包括在腳本中訪問SHORTURL test.js文件添加後,它沒有定義。

我有點困惑。

+0

Your title is so reddit':P' –

+1

@ŠimeVidas:neh,reddit會使用「釘牢它?」 :) – hugomg

回答

1

你的主要功能有調用類似,這將作爲一個腳本標記你的頭:

<script src="http://www.mydomain.com/file.php?callback=JSONP_callback"></script> 

callback=JSONP_callback,意味着該JSONP_callback將返回結果的JavaScript中調用。所以你的服務器知道調用哪個函數來顯示結果。在你的主頁上,你必須定義處理數據的函數。

function JSONP_callback(response) 
{ 
    alert(response.name); 
} 

然後你PHP或任何腳本你使用,你必須從你的回調調用的函數,這可以只要使用Javascript承認它是什麼:

// Within PHP it looks like: 
echo $_GET['callback'] . "(" . json_encode(array("name" => "Niels")) . ")"; 

// Which results in: 
JSONP_callback({ name : "Niels" }); 

這結果與功能因爲我們已經調用了頁面callback=JSONP_callback作爲參數。由於我們在主頁面中定義了function JSONP_callback(result),腳本將使用給定的數據執行此功能。

數個月前,我曾研究這個學校,我做了演示,也許你能以某種方式使用它:http://lutrasoft.nl/school/JSONP.html

+0

我想我明白了。但是,如果頁面中包含腳本,則該腳本的變量不可訪問?或者是否跨越到域策略? – GV1

+0

你必須將head標籤看作函數的調用者,在該函數中,你可以做任何你想做的事,因爲它在主頁上。腳本標籤僅爲主頁面提供數據。 – Niels

0

的問題是,腳本標記加載異步所以不是事物運行像

insert tag 
set shortURL 
use shortURL 
//your script finishes 

插入腳本只有一個機會運行在完成後

insert tag 
use shortURL //oops! 
//your script finishes 
set shortURL 

背後JSONP訣竅是,而不是換貨政... rning明文數據,我們返回什麼看起來像一個函數調用

//instead of setting a variable like "shortUrl = ..." 
// we instead call a function: 
on_have_shortUrl({"first_name":...}); 

因此,所有你需要做的是有一個on_have_shortUrl功能準備事先

function on_have_shortUrl(shortURL){ use shortURL here} 
insert script tag 
inserted script calls your function passing the data to it 

尼爾的回答推移更加詳細地介紹如何JSONP「協議「可以讓你爲回調函數和其他類似的東西選擇不同的名稱。