2011-02-12 59 views
0

我想提供一個可嵌入的JavaScript,它將從我的服務器獲取腳本。而後者會從用戶(我的可嵌入式js的頁面)中獲取一些細節並將其放回到我的服務器上。我如何去實現這一點。腳本標記破解+如何在AJAX的第二級之後進行通信

這是我提供的可嵌入式js。

<script> 
     (function() { 
      read="This is the data which is entered by the user"; 
      var istreet = document.createElement('script'); istreet.type = 'text/javascript'; istreet.async = true; 
      istreet.src = 'http://xyz.com/a.php; 
      (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(istreet); 
     })(); 

    </script> 

這是http://xyz.com/a.php

$('<div id="content"></div>').appendTo('body'); 
$('#content').html(' 
    Some html to inject to the page\'s dom . 
'); 
$.get("http://xyz.com/process.php?dataToProcess="+read,function(data){ 
alert(data); 
}); 

代碼,但我看到,$獲得( 「http://xyz.com/process.php?dataToProcess=」 +閱讀功能(數據){// 導致跨域Ajax請求

我不想解決跨域AJAX的問題。 我希望能夠與嵌入腳本雙方一間(通信和我的服務器)無縫地。

回答

0

如果您只需要GET請求,就可以使用JSON-P(http://en.wikipedia.org/wiki/JSON#JSONP)。

在JavaScript中,語法是這樣的: 「回調=」

$.getJSON("http://xyz.com/process.php?dataToProcess=" + encodeURIComponent(read) + "&callback=?", 
    function(result){ 
    alert(result); 
    }); 

的屬性告訴JQuery這是一個JSON-P請求。 JQuery將用一些任意的字符串替換「?」 (更多細節在這裏:http://api.jquery.com/jQuery.getJSON/)。

爲了使其正常工作,您還需要更改process.php處理程序。 PHP處理程序應首先讀取「回調」查詢參數的值,然後將響應包裝在該值中。

例如,如果$ .getJSON()發送的參數 「回調= ABCD」 到PHP頁面,PHP頁面應該返回:

abcd({"data": "json object with the result"}); 

有幾件事情需要注意:

  • 務必使用encodeURIComponent()將所有發送給服務器的用戶數據轉義出來。

  • 如果process.php修改用戶數據,那麼在使用GET請求時應該小心,因爲這可能會導致XSRF攻擊(http://en.wikipedia.org/wiki/Cross-site_request_forgery)。

相關問題