繁体   English   中英

无法通过Ajax连接到位于Web服务器上的php文件?

[英]cannot connect to php file located on webserver through ajax?

根据一些研究,我认为XmlHttpRequest不允许直接进行跨域数据交换,因此下面的代码无法连接到存储在webserver(1freehosting.com)上的getstopname.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文件(存储在其他Web服务器上)

<?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>" ;

  }

?>

看来您正在使用JQuery作为选择器,所以为什么不使用JQuery的ajax方法

https://api.jquery.com/jQuery.ajax/

crossDomain有一个选项。

您可以尝试允许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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM