0

我想提供一个可嵌入的 javascript,它将从我的服务器获取脚本。这反过来将从用户那里获得一些详细信息(具有我的可嵌入 js 的页面)并将其放回我的服务器上。我该如何实现这一目标。

这是我提供的可嵌入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);
});

但我看到 $.get("http://xyz.com/process.php?dataToProcess="+read,function(data){ // 导致跨域 ajax 请求

我不想解决跨域ajax 问题。我希望能够在两方(带有可嵌入脚本的一方和我的服务器)之间无缝通信。

4

2 回答 2

0

我使用这个跨域 iframe hack 在两个不同的域之间进行通信。我推荐阅读这个

http://softwareas.com/cross-domain-communication-with-iframes

于 2011-02-25T08:33:57.553 回答
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() 将参数“callback=abcd”发送到 php 页面,则 php 页面应该返回:

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

需要注意的几点:

  • 确保使用 encodeURIComponent() 转义您发送到服务器的任何用户数据;

  • 如果 process.php 修改了用户数据,在使用 GET 请求时应该小心,因为这可能导致 XSRF 攻击 (http://en.wikipedia.org/wiki/Cross-site_request_forgery)。

于 2011-02-13T05:08:45.503 回答