微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用PHP和Javascript / Ajax绕过CORS

我一直在努力解决这个问题几个小时,虽然我在网络开发方面没有受过教育而无法理解.继承人:

一个网站有一个脚本,他们从以下方式获取信息:

var url = "numbers.PHP";
parameters = "scoreid=" + document.getElementById('whatscore').value;
parameters += "&num=" + document.getElementById('num1b1').value;

xmlhttp2=GetXmlHttpObject();
if (xmlhttp2==null) {
    alert ("Your browser does not support XMLHTTP!");
    return;
}

xmlhttp2.onreadystatechange = function() {
    if (xmlhttp2.readyState==4) {
        scorespot.innerHTML=xmlhttp2.responseText;              // load 
        setscores(document.getElementById('gradelvl').value);   // set 
        document.getElementById('submitscorebtn').style.display="none";
    }
}
xmlhttp2.open("POST",url,true);
xmlhttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp2.setRequestHeader("Content-length",parameters.length);
xmlhttp2.setRequestHeader("Connection","close");
xmlhttp2.send(parameters);

我试图做同样的事情,但是当我尝试它时,我得到了交叉原点错误.我知道他们有办法用jsonp和其他东西来做,虽然我不知道从哪里开始这个.

当我尝试直接从他们的页面请求信息时,可以访问numbers.PHP页面,例如example.com/numbers.PHP?scoreid=131\u0026amp;num=41.我总是返回“错误:参数语法不正确”.

任何人都可以告诉我如何解决这个问题吗?我只熟悉PHP和Javascript,我对Ajax和其他东西或外部库都没有教育.

我感谢所有的帮助!
注意:我无法访问WEBSERVER.

解决方法

如果您无法访问您的服务器配置,并且您没有控制外部PHP脚本(假设它没有设置为反向代理),那么您绝对不能使用独立的JavaScript解决方案.

相反,您必须从您自己的本地PHP脚本发出外部请求.然后你将从Ajax调用你的本地PHP脚本,这将是有效的,因为你访问本地文件,因此不违反CORS.

以下是通过本地PHP脚本调用Ajax的示例.
想象一下您允许用户查找专辑名称的场景.用户输入歌曲的名称和艺术家.您向第三方API发出请求,并通过JavaScript警报通知将响应返回给用户.对于此示例,假设用户输入“Black”和“Pearl Jam”作为歌曲和艺术家姓名

使用HTML的Ajax POST到本地PHP脚本示例:

<html>
  <head>
  <!-- Load jQuery Library from Google -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
  </head>        

  <body>
    <h1> Ajax to local PHP Script Example: </h1>

    <form id="getArtist">
      Artist: <input type="text" placeholder="Pearl Jam">
      Song: <input type="text" placeholder="Black">
      <input type="submit" value="Click Here to Active Ajax Call">
    </form>

  </body>
</html>

<script type='text/javascript'>
$("#getArtist").submit(function(event) { //Listen to when the Submit is pressed
    event.preventDefault();  //Stop the submit from actually performing a submit
    $.post("local_script.PHP",{ song: "Black",artist: "Pearl Jam",dataType: "json"}) //prepare and execute post
        .done(function(response) { //Once we receive response from PHP script
            //Do something with the response:
            alert("The album name is: " +response);
            //Look into JSON.parse and JSON.stringify for accessing data 
         });
    });
</script>

PHP GET

<?PHP
$url = 'http://api.music.com/album';

$song = urlencode($_GET['song']));    //Need to url encode
$artist = urlencode($_GET['artist']); //Need to url encode

$response = file_get_contents($url .'?song=' .$song .'&artist=' .$artist);
    //**The url looks like http://api.music.com/album?song=Black&artist=Pearl+Jam

//** For purposes of this demo,we will manually assume the JSON response from the API:
$response = '{ "album": "Ten" }'; //(Raw JSON returned by API)
echo $response; //Return the response back to AJAX,assuming it is already returned as JSON. Else encode it json_encode($response)

PHP POST(使用curl)

<?PHP
$url = 'http://api.music.com/album';

$song = urlencode($_GET['song']));    //Need to url encode  
$artist = urlencode($_GET['artist']); //Need to url encode

//$headers = array("Key: " ."Value","Key: " ."Value",//Set any headers,if required.

$post = 'song=' .$song .'&artist=' .$artist; //Prepare Post parameters

/* Configure Curl */
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);    
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);  //Allow music api to send response
curl_setopt($ch,CURLOPT_POST,1);            //Signifyd that we are doing a POST request
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);
//curl_setopt($curl,CURLOPT_HTTPHEADER,$header); //Only if you need to send headers


/* Get Response */
$response = curl_exec($ch);

//** For purposes of this demo,we will manually assume the JSON response from the API:
$response = '{ "album": "Ten" }'; //(Raw JSON returned by API)

echo $response; //Send response back to Ajax,assuming it was already returned in JSON. Else encode it.

进一步阅读Ajax请求:https://api.jquery.com/jquery.get/
 https://api.jquery.com/jquery.post/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐