Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

php - Remote POST request with jQuery and Ajax

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

How it works:

  1. Create Proxy.php and paste the content.
  2. Make a page originally sends request to send an AJAX request to proxy.php instead of the target server.
  3. The request will be redirected to the target server.
  4. 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

EDIT: what i meant is using your server to submit fault request to target server. anyway it is not so bad for adding some simple authentication for your users :)

some/where/in/your/server/proxy.php

<?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);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...