用PHP和Javascript / Ajax绕过CORS

其他

尽管我对Web开发的知识不足,但我一直在尝试解决数小时。情况如下:

另一个网站具有一个脚本,他们可以通过以下方式获取信息:

    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&num=41。我总是返回“错误:参数语法错误”。

有人可以告诉我如何解决此问题吗?我只非常了解PHP和Javascript,对Ajax和其他东西或外部库没有很好的了解。

我感谢所有帮助!注意:我没有访问网络服务器。

用户名

如果您无权访问服务器配置,并且不控制外部php脚本(假设未将其设置为充当反向代理),那么您绝对不能为此使用独立的javascript解决方案。

相反,您必须从您自己的本地php脚本发出外部请求。然后,您将从Ajax调用本地php脚本,这起作用,因为您正在访问本地文件,因此不会违反CORS。

这是通过本地PHP脚本进行Ajax调用的示例。

想象一个场景,允许用户查找相册名称。用户输入歌曲的名称和艺术家。您向第3方api发送请求,然后通过JavaScript警报通知将响应返回给用户。对于此示例,假设用户输入“ Black”和“ Pearl Jam”作为歌曲和歌手姓名

Ajax POST到带有HTML示例的本地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/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章