4

我需要用户导航到某个页面,该页面有一个充满有用文本的 div。然后单击我的书签并将该 div 中的文本发送回我的服务器,该服务器与当前域不同。我已成功在小书签单击上插入 jQuery 并选择了文本。现在我需要想办法将文本跨域发送到我的服务器。我用 jQuery 尝试了 JSONP,但我的文本对于 url 来说太长了。我的第二个想法是打开一个新窗口并从我的域加载一个页面,然后以某种方式将选定的文本插入新窗口,之后用户可以单击提交并将该数据发布到我的服务器。由于 javascript 跨站点原因,这不起作用。有人对此有任何经验或想法吗?谢谢。

4

3 回答 3

5

生成一个表单(使用 DOM)并发布数据(您可能想要定位一个 iframe,但它会被触发并忘记)。

于 2010-02-03T21:01:33.257 回答
4

这是一个将文本发布到远程服务器的示例。如果你想改变你有 iframe 的页面,你可以在远程服务器上打印 javascript 来表示成功。或者一个弹出窗口说它完成了。在远程服务器上,您可以打印此弹出窗口:

<script> parent.document.getElementById('postmessage').style.display='block'; parent.alert('Successfully posted');</script>

在您要发送信息的网页上,像这样制作一个表单和 iframe。

<span id="postmessage" style="display:none">Success Message</span>
<form action="http://www.remoteserver.com/upload_test.php" method="post" target="post_to_iframe">
  <input type="hidden" value="the text to send to remote server" />
  <input type="submit" value="Submit" />
</form>

<!-- When you submit the form it will submit to this iFrame without refreshing the page and it will make the popup and display the message. -->
<iframe name="post_to_iframe" style="width: 600px; height: 500px;"></iframe>
于 2012-03-16T19:47:29.267 回答
3

使用 javascript 创建 iframe。然后将表单添加到 iframe 并提交。提交表单后,将触发 onload 回调。

var i=document.createElement('iframe');
i.setAttribute('name', 'frame-id');
i.setAttribute('id', 'frame-id');
i.setAttribute('allowtransparency', 'true');
i.setAttribute('style', 'border: 0; width: 1px; height: 1px; position: absolute; left: 0; top: 0;');
i.setAttribute('onload', 'iframeFormSubmitted();');

document.body.appendChild(i);

var html = '<html><body>' +
'<form action="/post_url" method="post" id="iframe-form" accept-charset="utf-8">' +
'<input type="hidden" name="id" value="' + your_text + '"/>' +
'</form>' +
'<scr'+"ipt>var e=encodeURIComponent,w=window,d=document,f=d.getElementById('f');" +
"d.getElementById('iframe-form').submit();" +
'</scr'+"ipt></body></html>";

window.frames['frame-id'].document.write(html);
于 2012-03-31T00:56:28.017 回答