用jQuery和Ajax远程POST请求 [英] Remote POST request with jQuery and Ajax
问题描述
我需要做一个POST请求远程域trhough阿贾克斯,我知道有同源策略的限制,但我读过,也有可能使PHP的桥梁我的服务器转发请求
I need to do a POST request to a remote domain trhough Ajax, I know there is the restriction of the Same-Origin Policy but I've read that could be possible make a bridge in PHP on my server to forward the request.
事实上,我已经不是如何写这个桥,我无法找到的信息在谷歌的想法。
我想我需要使用卷曲。
The fact is that I've not idea of how to write this bridge and I can't find info on Google.
I guess I need to use CURL.
有人能解释我如何写一个?
Can someone explain me how to write one?
推荐答案
如果你需要代理或桥,你可以尝试如下: 你可以实现一个简单的AJAX调用到PHP脚本和重定向POST给你想要的另一台服务器。
If you need a proxy or "Bridge", you can try as below: You can achieve a simple AJAX call to that PHP script and redirect that POST to another server you desired.
它是如何工作的:
- 创建Proxy.php和粘贴内容。
- 请在页面最初将请求发送一个Ajax请求proxy.php目标服务器来代替。
- 该请求将被重定向到目标服务器。
- 您可以选择设置选项 CURLOPT_RETURNTRANSFER 如果你想要的结果。
- Create Proxy.php and paste the content.
- Make a page originally sends request to send an AJAX request to proxy.php instead of the target server.
- The request will be redirected to the target server.
- You can optionally set option CURLOPT_RETURNTRANSFER if you want the result.
请记住为把一些服务器的身份验证方法首先,因为我已经写的无在这个例子中,或该网页将是一个很好的垃圾机
Please remember to put some server authentication methods first, as I have written none in the example, or that page would be a nice spam machine
编辑:使用您的服务器提交的故障请求到目标服务器我的意思是。反正也不是那么糟糕加入一些简单的身份验证用户:)的
<?php
/* You might want some authentication here */
/* check authentication */
/* Authentication ended. */
$url = 'http://target.com/api'; //Edit your target here
foreach($_GET as $getname => $getvar) {
$fields[$getname] = urlencode($getvar); //for proxying get request to POST.
}
foreach($_POST as $postname => $postvar) {
$fields[$postname ] = urlencode($postvar); //for proxying POST requests.
}
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
我假定你知道POST发送Ajax请求已经的方式。如果不知为何,你都没有,只是尝试读取 http://www.openjs.com/scripts/jx/jx.php
I assumes you know the way of sending POST ajax request already. If somehow you are not, just try to read http://www.openjs.com/scripts/jx/jx.php
这篇关于用jQuery和Ajax远程POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!