2009-10-13 63 views
2

我创建了一个快速原型作为更大项目的概念证明。我需要创建一个可用的跨域POST请求,并且我有jQuery可用。jQuery POST请求 - 提交<form><iframe>

因为我假设(请纠正我,如果我错了),$ .ajax()将无法正常工作,因为发出POST请求的页面与接收请求的服务器在不同的域中,猜测最好的解决方案是使用JavaScript创建一个<iframe>,然后在那里插入一个< form method =“post”>,其中包含隐藏的输入和我的POST数据,然后提交。

我到底该怎么做? (请提供代码示例如果可能的话)。

到目前为止,我有这样的:

<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> 

我知道我需要使用提交()方法,但我不知道,看起来到底是什么喜欢,特别是因为<形式>是在<iframe>和我应该只调用提交()后<iframe>已加载。

请让我知道,如果您有任何建议/想法,发现任何错误,可以推荐更好的方法,等等。

(顺便说一句,我做了前对堆栈溢出天一些搜索和可以发誓,我发现在一个相关的问题一些代码,将是有益的。今天我找不到,但...)

回答

4

p是后期的数组变量和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); 
    }; 
+0

非常感谢您的帮助,但我想使用jQuery来增强跨浏览器的兼容性,并且我认为我需要使用