javascript - Working around the Same-Origin Policy? -
i have file on local installed xampp called test.php. when go http://127.0.0.1/test.php , execute it, script should post values id , name site http://otherdomain.com/post.php , put output data. not work because of same-origin policy. when trace packages error calles "ns_error_dom_bad_uri". question is, there anyway make possible anyways without needing have access http://otherdomain.com/?
test.php
<script> $(window).load(function(){ var url = "http://otherdomain.com/post.php"; $.post(url,{id : "12", name : "john"}, function(data) { alert("it worked!"); }); }); </script>
update
i changed following set up. have 2 files called send.php , proxy.php. send request send.php proxy.php , proxy.php sent actual request otherdomain.com. when execute send.php now(means pressing button) result "error: 403 forbidden access".
send.php
<!doctype html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $.post("proxy.php", function(data,status){ alert("data: " + data + "\nstatus: " + status); }); }); }); </script> </head> <body> <button>send data</button> </body> </html>
proxy.php
<?php $ch = curl_init(); curl_setopt($ch, curlopt_url,"http://otherdomain.com/data"); curl_setopt($ch, curlopt_post, 1); curl_setopt($ch, curlopt_postfields,"name=jack&age=23"); curl_setopt($ch, curlopt_returntransfer, true); $server_output = curl_exec ($ch); curl_close ($ch); if ($server_output == "ok") { echo "it worked!"; } else { echo "error: " . $server_output; } ?>
you must use proxy file in order avoid same origin policies restrictions. inside proxy.php can make request otherdomain.com via curl or other http libraries. call proxy file via javascript instead of calling otherdomain.com directly.
Comments
Post a Comment