实现一个javascript-CORS示例

实现一个javascript-CORS示例,javascript,php,ajax,cors,Javascript,Php,Ajax,Cors,我正在尝试做一个跨源ajax请求(CORS),我从MJHALL找到了一个启动代码 当在我们的内部网络(2个独立的域)上执行该示例时,该示例非常有效并返回一个结果。然而,当我试图扩展它以包含我自己的一些代码时,我得到了这个错误 跨源请求被阻止:同源策略不允许读取位于内部URL.67/dirLib/listing2.php的远程资源。(原因:缺少CORS标头“访问控制允许原点”) 这是我的密码。我的问题出现在“清单2”中。第一个代码片段是MJHALL示例中的“清单1”,我只需插入我的内部URL 您可

我正在尝试做一个跨源ajax请求(CORS),我从MJHALL找到了一个启动代码

当在我们的内部网络(2个独立的域)上执行该示例时,该示例非常有效并返回一个结果。然而,当我试图扩展它以包含我自己的一些代码时,我得到了这个错误

跨源请求被阻止:同源策略不允许读取位于内部URL.67/dirLib/listing2.php的远程资源。(原因:缺少CORS标头“访问控制允许原点”)

这是我的密码。我的问题出现在“清单2”中。第一个代码片段是MJHALL示例中的“清单1”,我只需插入我的内部URL

您可以忽略清单2中的大部分代码。当我尝试在清单2中的“$rf->p=json_decode($json);”这一行引用我自己的代码时,问题就出现了。在这里,我只是尝试将传入数据存储在类$rf中的公共“$p”变量中。如果我删除这条线,就不会出现交叉原点错误。如何引用自己的代码

<!doctype html>
 <html lang="en">
 <head>
   <script type="text/javascript">

     window.onload = doAjax();

     function doAjax() {
        var url         = "http://my internal URL.67/i/listing2.php";
        var request     = JSON.stringify({searchterm:"two"})
        var xmlhttp     = new XMLHttpRequest();

        xmlhttp.open("POST", url);
        xmlhttp.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "http://my internal calling URL.23");
        xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
        xmlhttp.setRequestHeader("Access-Control-Request-Headers", "X-Requested-With, accept, content-type");

        xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
           var jsondata = JSON.parse(xmlhttp.responseText);
           document.getElementById("id01").innerHTML = xmlhttp.responseText;
           document.getElementById("id02").innerHTML = jsondata.word;
           document.getElementById("id03").innerHTML = jsondata.RF;
       }
     };

     xmlhttp.send(request);
  }

</script>
</head>

<body>
 <div id="id01"></div>
 <div id="id02"></div>
 <div id="id03"></div>
</body>

</html>
这里的代码是简化的发送代码

<!doctype html>
<html lang="en">

<head>
 <script type="text/javascript">

  window.onload = doAjax();

  function doAjax() {
      var url         = "http://receiving URL/listing3.php";
      var request     = JSON.stringify({searchterm:"two"})
      var xmlhttp     = new XMLHttpRequest();

      xmlhttp.open("POST", url);
      xmlhttp.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
      xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "http://sending URL");
      xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
      xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
      xmlhttp.setRequestHeader("Access-Control-Request-Headers", "X-Requested-With, accept, content-type");

      xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          var jsondata = JSON.parse(xmlhttp.responseText);
          document.getElementById("id01").innerHTML = xmlhttp.responseText;
          document.getElementById("id02").innerHTML = jsondata.word;
      }
  };

  xmlhttp.send(request);
}

 </script>
 </head>

<body>
<div id="id01"></div>
<div id="id02"></div>
<div id="id03"></div>
</body>

</html>

window.onload=doAjax();
函数doAjax(){
变量url=”http://receiving URL/listing3.php”;
var request=JSON.stringify({searchterm:“two”})
var xmlhttp=new XMLHttpRequest();
open(“POST”,url);
setRequestHeader(“内容类型”,“应用程序/json;字符集=UTF-8”);
setRequestHeader(“访问控制允许源”http://sending 网址“);
setRequestHeader(“访问控制允许方法”、“获取、发布、选项”);
setRequestHeader(“访问控制允许头”,“内容类型”);
setRequestHeader(“访问控制请求头”,“X-Request-With,accept,content-type”);
xmlhttp.onreadystatechange=函数(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
var jsondata=JSON.parse(xmlhttp.responseText);
document.getElementById(“id01”).innerHTML=xmlhttp.responseText;
document.getElementById(“id02”).innerHTML=jsondata.word;
}
};
发送(请求);
}
这是简化的接收代码

<?php

$dictionary = array('one' => 'uno', 'two' => 'due', 'three' => 'tre');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'POST') {
        header('Access-Control-Allow-Origin:  http://sending URL');
        header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
    }
    exit;
}

$json = file_get_contents('php://input');
$obj = json_decode($json);
if (array_key_exists($obj->searchterm, $dictionary)) {
    $response = json_encode(array('result' => 1, 'word' => $dictionary[$obj->searchterm], 'RF' => var_dump($_POST)));
}

header('Content-type: application/json');
header('Access-Control-Allow-Origin: http://sending URL');
echo $response;

?>

这是一个修改过的接收应用程序,它查找一个表值并返回它

<?php
$db = new mysqli("my database connection", "my user", "my password", "my database");

$dictionary = array('one' => 'uno', 'two' => 'due', 'three' => 'tre');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'POST') {
        header('Access-Control-Allow-Origin:  http://my calling URL');
        header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
    }
    exit;
}

$json = file_get_contents('php://input');
$obj = json_decode($json);
if (array_key_exists($obj->searchterm, $dictionary)) {

        $sql = 'select myCol from myTable where myCol=myVariable';
        if ( $result = $db->query($sql) )
        {
            if ($result->num_rows > 0)
            {
                $l = mysqli_fetch_all( $result, $resulttype = MYSQLI_ASSOC );
                $RF = $l[0];
            }else{
                $RF=new StdClass;
            }
        }

    $response = json_encode(array('result' => 1, 'word' =>  $dictionary[$obj->searchterm], 'RF' => $RF));
}

header('Content-type: application/json');
header('Access-Control-Allow-Origin: http://my calling URL');
echo $response;

?>

经过一天的困惑,我终于找到了工作。以下是我的想法和一些观察结果。欢迎就如何改进提出意见

这是一个有效的例子

域A=发送CORS ajax请求

域B=接收CORS ajax请求和响应

从域a上的浏览器启动的发送应用程序

页眉中包含javascript以简化编码的显示

<!doctype html>
<html lang="en">

<head>
    <script type="text/javascript">
        String.prototype.trim = function (){
            return this.replace(/^\s*/, "").replace(/\s*$/, "");
        }

        var g = {};

        g.formClass = function()
        {
            this.callBack, this.sendObj = {}, this.resultObj = {};

            this.getRequest = function()
            {
                if (document.getElementById("reckey").value.trim() == '')
                {
                    alert('Enter column1');
                }else{
                    this.sendObj['reckey'] = document.getElementById("reckey").value;
                    this.callBack = 'displayResult';
                    this.doAjax();
                }
            };

            this.displayResult = function(response)
            {
             this.resultObj = JSON.parse(response);
              document.getElementById("JSONresposeDisplay").innerHTML ='JSON response: '+response;
              document.getElementById("column1").innerHTML = this.resultObj.column1;
              document.getElementById("column2").innerHTML = this.resultObj.column2;
              document.getElementById("column3").innerHTML = this.resultObj.column3;
            };

            this.doAjax = function() {
                var url     = "http://999.999.99.9/receiveRequest.php";
                var request = JSON.stringify(g.c.sendObj)
                var xhr     = new XMLHttpRequest();

                xhr.open("POST", url);
                xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
                xhr.setRequestHeader("Access-Control-Allow-Origin", "http://888.888.88.8");
                xhr.setRequestHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
                xhr.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
                xhr.setRequestHeader("Access-Control-Request-Headers", "X-Requested-With, accept, content-type");

                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && xhr.status == 200)
                        g.c[g.c.callBack](xhr.response);            
                };

                xhr.send(request);
            };

            this.onBodyLoader = function(obj)
            {
                this.ajaxRequest = document.getElementById('ajaxRequest');
                this.ajaxRequest.addEventListener("click",function(){g.c.getRequest();}, false);
            };

        }
        g.c = new g.formClass;
    </script>
</head>

<body onLoad="g.c.onBodyLoader(this);">
    <div id="JSONresposeDisplay"></div>
    <div id="" class="">
        <table>
            <tr>
                <td>Enter Job #</td>
                <td>
                    <input type="text" id="reckey">&nbsp;
                    <input type="button" id="ajaxRequest" value="Request Info via ajax/JSON">
                </td>
            </tr><tr>
                <td>Job</td>
                <td id='column1'></td>
            </tr><tr>
                <td>Client</td>
                <td id='column2'></td>
            </tr><tr>
                <td>Project</td>
                <td id='column3'></td>
            </tr>
        </table>     
    </div>
</body>

</html>

String.prototype.trim=函数(){
返回此。替换(/^\s*/,“”)。替换(/\s*$/,“”);
}
var g={};
g、 formClass=函数()
{
this.callBack,this.sendObj={},this.resultObj={};
this.getRequest=函数()
{
if(document.getElementById(“reckey”).value.trim()='')
{
警报(“输入第1列”);
}否则{
this.sendObj['reckey']=document.getElementById(“reckey”).value;
this.callBack='displayResult';
这是doAjax();
}
};
this.displayResult=函数(响应)
{
this.resultObj=JSON.parse(响应);
document.getElementById(“JSONresposeDisplay”).innerHTML='JSON response:'+response;
document.getElementById(“column1”).innerHTML=this.resultObj.column1;
document.getElementById(“column2”).innerHTML=this.resultObj.column2;
document.getElementById(“column3”).innerHTML=this.resultObj.column3;
};
this.doAjax=function(){
变量url=”http://999.999.99.9/receiveRequest.php";
var request=JSON.stringify(g.c.sendObj)
var xhr=new XMLHttpRequest();
xhr.open(“POST”,url);
setRequestHeader(“内容类型”,“应用程序/json;字符集=UTF-8”);
setRequestHeader(“访问控制允许源站”http://888.888.88.8");
setRequestHeader(“访问控制允许方法”、“POST、选项”);
setRequestHeader(“访问控制允许头”,“内容类型”);
setRequestHeader(“访问控制请求头”,“X-Request-With,accept,content-type”);
xhr.onreadystatechange=函数(){
如果(xhr.readyState==4&&xhr.status==200)
g、 c[g.c.回调](xhr.响应);
};
发送(请求);
};
this.onBodyLoader=函数(obj)
{
this.ajaxRequest=document.getElementById('ajaxRequest');
this.ajaxRequest.addEventListener(“单击”,函数(){g.c.getRequest();},false);
};
}
g、 c=新的g.formClass;
入职#
工作
客户
项目
这是域B上的接收应用程序

    <?php

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'POST') {
        header('Access-Control-Allow-Origin:  http://888.888.88.8');
        header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
    }
    exit;
}

$json = file_get_contents('php://input');
$obj = json_decode($json);
    $db = new mysqli("ip address of server", "user login", "password", "dataBase");

    $sql = 'select column1, column2, column3 from table where column1='.$obj->reckey;
    if ( $result = $db->query($sql) )
    {
        if ($result->num_rows > 0)
        {
            $l = mysqli_fetch_all( $result, $resulttype = MYSQLI_ASSOC );
            $resultObject = $l[0];
        }else{
            $resultObject=new StdClass;
        }
    }

    $response = json_encode($resultObject);

header('Content-type: application/json');
header('Access-Control-Allow-Origin: http://888.888.88.8');
echo $response;

?>

我的意见:

  • 我使用IP地址是因为我没有这两台服务器的域名。所以这和我在网上找到的不同

  • 出于某种我不理解的原因,发送请求的浏览器必须从域服务器启动。我无法使用的URL从其他机器调用它
    <!doctype html>
    <html lang="en">
    
    <head>
        <script type="text/javascript">
            String.prototype.trim = function (){
                return this.replace(/^\s*/, "").replace(/\s*$/, "");
            }
    
            var g = {};
    
            g.formClass = function()
            {
                this.callBack, this.sendObj = {}, this.resultObj = {};
    
                this.getRequest = function()
                {
                    if (document.getElementById("reckey").value.trim() == '')
                    {
                        alert('Enter column1');
                    }else{
                        this.sendObj['reckey'] = document.getElementById("reckey").value;
                        this.callBack = 'displayResult';
                        this.doAjax();
                    }
                };
    
                this.displayResult = function(response)
                {
                 this.resultObj = JSON.parse(response);
                  document.getElementById("JSONresposeDisplay").innerHTML ='JSON response: '+response;
                  document.getElementById("column1").innerHTML = this.resultObj.column1;
                  document.getElementById("column2").innerHTML = this.resultObj.column2;
                  document.getElementById("column3").innerHTML = this.resultObj.column3;
                };
    
                this.doAjax = function() {
                    var url     = "http://999.999.99.9/receiveRequest.php";
                    var request = JSON.stringify(g.c.sendObj)
                    var xhr     = new XMLHttpRequest();
    
                    xhr.open("POST", url);
                    xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
                    xhr.setRequestHeader("Access-Control-Allow-Origin", "http://888.888.88.8");
                    xhr.setRequestHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
                    xhr.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
                    xhr.setRequestHeader("Access-Control-Request-Headers", "X-Requested-With, accept, content-type");
    
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState == 4 && xhr.status == 200)
                            g.c[g.c.callBack](xhr.response);            
                    };
    
                    xhr.send(request);
                };
    
                this.onBodyLoader = function(obj)
                {
                    this.ajaxRequest = document.getElementById('ajaxRequest');
                    this.ajaxRequest.addEventListener("click",function(){g.c.getRequest();}, false);
                };
    
            }
            g.c = new g.formClass;
        </script>
    </head>
    
    <body onLoad="g.c.onBodyLoader(this);">
        <div id="JSONresposeDisplay"></div>
        <div id="" class="">
            <table>
                <tr>
                    <td>Enter Job #</td>
                    <td>
                        <input type="text" id="reckey">&nbsp;
                        <input type="button" id="ajaxRequest" value="Request Info via ajax/JSON">
                    </td>
                </tr><tr>
                    <td>Job</td>
                    <td id='column1'></td>
                </tr><tr>
                    <td>Client</td>
                    <td id='column2'></td>
                </tr><tr>
                    <td>Project</td>
                    <td id='column3'></td>
                </tr>
            </table>     
        </div>
    </body>
    
    </html>
    
        <?php
    
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'POST') {
            header('Access-Control-Allow-Origin:  http://888.888.88.8');
            header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
        }
        exit;
    }
    
    $json = file_get_contents('php://input');
    $obj = json_decode($json);
        $db = new mysqli("ip address of server", "user login", "password", "dataBase");
    
        $sql = 'select column1, column2, column3 from table where column1='.$obj->reckey;
        if ( $result = $db->query($sql) )
        {
            if ($result->num_rows > 0)
            {
                $l = mysqli_fetch_all( $result, $resulttype = MYSQLI_ASSOC );
                $resultObject = $l[0];
            }else{
                $resultObject=new StdClass;
            }
        }
    
        $response = json_encode($resultObject);
    
    header('Content-type: application/json');
    header('Access-Control-Allow-Origin: http://888.888.88.8');
    echo $response;
    
    ?>