使用 PHP 和 Javascript/Ajax 绕过 CORS [英] Bypassing CORS with PHP and Javascript/Ajax

查看:30
本文介绍了使用 PHP 和 Javascript/Ajax 绕过 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了几个小时来解决这个问题,尽管我在 Web 开发方面没有受过教育,无法理解.情况如下:

I've been trying to figure this out for hours, though I'm too uneducated in web development to understand. Heres the case:

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

Another website has a script that they obtain information from the following way:

    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 和其他方法来做这件事的方法,尽管我完全不知道从哪里开始.

I've attempted to do the same thing, though when I attempt it I get the cross-origin error. I know their are ways to do it with jsonp and other things, though I have no clue where to start at all for this.

当我尝试直接从他们的页面请求信息时,numbers.php 页面,例如 example.com/numbers.php?scoreid=131&num=41 .我总是收到错误:不正确的参数语法".

When I attempt to directly request information from their page, the numbers.php page, such as example.com/numbers.php?scoreid=131&num=41 . I always get returned with "Error: incorrect parameter syntax".

谁能告诉我如何解决这个问题?我只知道 PHP 和 Javascript,我对 Ajax 和其他东西或外部库非常缺乏教育.

Can anybody please tell me how I would fix this in my case? I only know PHP and Javascript well, I'm very uneducated with Ajax and other things or external libraries.

我感谢所有帮助!注意:我无法访问网络服务器.

I appreciate all help whatsoever! NOTICE: I DO NOT HAVE ACCESS TO THE WEBSERVER.

推荐答案

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

If you do not have access to your server configuration, and if you do not control the external php script (assuming it's not set up to serve as a reverse proxy), then you absolutely cannot use a standalone javascript solution for this.

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

Rather, you would have to make the external request from your own local php script. Then you would call your local php script from Ajax, and this will work since you are accessing a local file, and thus not violating CORS.

这是通过本地 PHP 脚本调用 Ajax 的示例.

想象一个允许用户查找专辑名称的场景.用户输入歌曲名称和艺术家.您向第 3 方 api 发出请求,并通过 JavaScript 警报通知将响应返回给用户.对于此示例,假设用户输入Black"和Pearl Jam"作为歌曲和艺术家名称

Here is an example of an Ajax call thru a local PHP script.

Imagine a scenario where you allow users to lookup an album name. The user enters the name of the song, and the artist. You make a request to a 3rd party api, and return the response back to the user via a JavaScript alert notification. For this example, assume the user enters 'Black' and 'Pearl Jam' as the song and artist names

使用 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 获取

<?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.得到/
https://api.jquery.com/jquery.post/

Further reading on Ajax requests:
https://api.jquery.com/jquery.get/
https://api.jquery.com/jquery.post/

这篇关于使用 PHP 和 Javascript/Ajax 绕过 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆