簡體   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