JSONP请求有限制: 第一,不能跳出两层, 第二,不支持POST.
往往解决跨域POST请求的方案是个"古老"方法, 请求同域下的iframe.
服务器端:
需要附加头信息:
[php] view plaincopy
- header(‘Access-Control-Allow-Origin: *‘);
- header(‘Access-Control-Allow-Methods: POST‘);
- header(‘Access-Control-Max-Age: 1000‘);
返回带有CALLBACK的串:
[php] view plaincopy
- <script type=‘text/javascript‘>document.domain=‘xxx.com‘;Callback({"ret":0,"error":"xxx","data":null});</script>
这里要注意,这里的 document.domain=‘xxx.com‘;这个domain是服务器端和前端都要定义的.
前端:
[php] view plaincopy
- <section>
- <form name="data_upload" action="http://request.com" method="post" target="upload_frame" onsubmit="return initUpload(this)" enctype="multipart/form-data">
- ......
- <iframe src="" id="upload_frame" name="upload_frame" style="display: none"></iframe>
- </section>
[php] view plaincopy
- <script>
- function initUpload(formEle) {
- ....
- document.domain=‘xxx.com‘;
- document.forms[‘data_upload‘].submit();
- }
- </script>
时间: 2024-10-13 08:40:20