【问题标题】:jQuery POST request - submitting a <form> inside of an <iframe>jQuery POST 请求 - 在 <iframe> 中提交 <form>
【发布时间】:2010-12-06 10:04:08
【问题描述】:

我正在创建一个快速原型,作为更大项目的概念验证。我需要创建一个有效的跨域 POST 请求,并且我有可用的 jQuery。

由于我假设(如果我错了,请纠正我)$.ajax() 将不起作用,因为发出 POST 请求的页面与接收请求的服务器位于不同的域中,我猜最好的解决方案是使用 JavaScript 创建一个

我该怎么做呢? (如果可能,请提供代码示例。)

到目前为止,我有这个:

<button type="button" name="button">Make Cross-Domain POST Request</button>

<script>
  $('button').click(function() {
    $('body').append('<iframe id="post_frame" style="width: 0; height: 0; border: none;"></iframe>');
    setTimeout(function() {
      var frame_body = $('#post_frame').contents().find('body');
      frame_body.append('<form action="..." method="post"><input type="hidden" name="foo" value="bar" /><input type="submit" /></form>');
      // not sure what goes here (should submit the form in the iframed document once it has loaded)
    }, 1);
  });
</script>

我知道我需要使用 submit() 方法,但我不知道具体是什么样的,特别是因为

【问题讨论】:

    标签: jquery forms iframe post cross-domain


    【解决方案1】:

    p 是一个 post 变量数组,to 是你的操作

       var issuePOST = function(to, p) {
            var myForm = document.createElement("form");
            myForm.method = "post";
            myForm.action = to;
            if (p) {
                for (var k in p) {
                    var myInput = document.createElement("input");
                    myInput.setAttribute("name", k);
                    myInput.setAttribute("value", p[k]);
                    myForm.appendChild(myInput);
                }
            }
            document.body.appendChild(myForm);
            myForm.submit();
            document.body.removeChild(myForm);
        };
    

    【讨论】:

    • 非常感谢您的帮助,但我想使用 jQuery 来增强跨浏览器的兼容性,我想我需要使用
    • 上面的代码应该适用于所有浏览器,它使用的基本javascript在所有浏览器中都是相同的。你可以把它放在一个 iframe 中......
    • 要解决您的跨域问题,您不需要使用 iframe。您可以让您的 ajax 请求使用跨域工作的 jsonp 对象。只需在 ajax 调用中添加 datatype:jsonp 即可跨域工作。
    • 老兄,你刚刚把我的头发 all 拉出来了 :-) 你建议的 key 元素是“document.body ”。出于某种原因,从 iframe 中发布时需要这样做。否则,仅使用“文档”就足够了……我不知道为什么。
    【解决方案2】:

    this question 中的 JavaScript sn-p 将从 IFrame 跨域发布。

    【讨论】:

      【解决方案3】:

      $("#post_frame").contents().find('form').submit();
      

      在追加之后。

      【讨论】:

        猜你喜欢
        • 2016-03-21
        • 1970-01-01
        • 2016-12-20
        • 2017-02-18
        • 2018-09-14
        • 1970-01-01
        • 2018-12-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多