2014-03-04 47 views
0

基于我经历的一些研究,我相信XmlHttpRequest不允许直接跨域数据交换。这样我的下面的代码就不会连接到存储在网络服务器(1freehosting.com)上的getstopname.php文件。无法通过ajax连接到位于网络服务器上的php文件?

我该如何转换我的下面的Java脚本代码,以便它可以直接访问存储在远程Web服务器上的PHP文件?

function getDirection(str) 
       { 
       if (str=="") 
       { 
       document.getElementById("select-choice-direction").innerHTML=""; 
       return; 
       } 

       if (window.XMLHttpRequest) 
       { 
       xmlhttp=new XMLHttpRequest(); 
       } 
       else 
       { 
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
       } 
       xmlhttp.onreadystatechange=function() 
       { 
       if (xmlhttp.readyState==4 && xmlhttp.status==200) 
        { 

        $('#select-choice-stopname').html(xmlhttp.responseText).selectmenu("refresh"); 
        $('#select-choice-stopname-postuser').html(xmlhttp.responseText).selectmenu("refresh"); 
       } 
       } 
       xmlhttp.open("GET","http://www.xyz.com/getstopname.php?direction="+str.value+"&bus="+busnum+"&dayofweek="+dayofweek,true); 
       xmlhttp.send(); 
       } 

getstopname.php文件(存储在不同势网页的网络服务器)

<?php 

$bus = intval($_GET['bus']); 
$q = $_GET['direction']; 
$dayofweek = $_GET['dayofweek']; 

$con=mysqli_connect("xyz.com","root","root123","db1","3306"); 

ct_db($con,"db1"); 

$result = mysqli_query($con,"SELECT StopNames FROM cfv_busstopnames WHERE UniqueBusId = '".$q."' and busnumber = ".$bus." and Dayofweek = '".$dayofweek."' "); 

    echo "<option>" . "Pick Stop Names? ". "</option>" ; 

while($row = mysqli_fetch_array($result)) 
    { 

    echo "<option>" . $row['StopNames'] . "</option>" ; 

    } 

?> 
+0

[同源策略(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript)适用于这种情况。您需要将该文件放在同一主机上,以便您可以使用相对URI。但是,您可能总是通过服务器代理文件,例如'get_file.php?xyz.com ...'。 –

+0

它工作正常,如果我同时在同一个Web服务器上承载这两个文件。我什至尝试过的瓦特和它工作正常的问题是,当我尝试从我的本地主机访问Ajax代码的PHP文件,在不同的网络服务器上在线托管的PHP文件。 –

+0

好吧,既然你拥有两台主机,你总是可以设置[CORS](https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS)。 –

回答

0

你可以试着让CORS:

截至getstopname.php顶部:

<?php 

header("Access-Control-Allow-Origin: *"); //remember to replace the * with the domain the JavaScript is running from 

$bus = intval($_GET['bus']); 
$q = $_GET['direction']; 
$dayofweek = $_GET['dayofweek']; 

//rest of the code 
相关问题