【问题标题】:unable to make cross domain calls using jquery ajax method?无法使用 jquery ajax 方法进行跨域调用?
【发布时间】:2014-03-09 12:24:14
【问题描述】:

当我尝试使用 wamp 从本地主机调用位于远程 Web 服务器上的 php 文件时,以下 JQuery Ajax 方法不起作用。但是,如果它们都在同一个网络服务器上,它就可以正常工作。我相信我已经打开了跨域仍然无法进行跨域调用?

  <script>
             $(function() {

                $("#callAjax").click(function() {
                    var theName = $.trim($("#theName").val());

                    if(theName.length > 0)
                    {
                        $.ajax({
                          type: "GET",
                          url: "http://www.bcbustransit.uni.me/callajax.php",
                          data: ({name: theName}),
                          crossDomain: true,
                          cache: false,
                          dataType: "text",
                          success: onSuccess
                        });
                    }
                });

                $("#resultLog").ajaxError(function(event, request, settings, exception) {
                 $("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
                });

                function onSuccess(data)
                {
                    $("#resultLog").html("Result: " + data);
                }

            });


        </script>

.

<?php

$con=mysqli_connect("freehosting","xyz","xyz","xyz","3306");

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }


mysqli_select_db($con,"u197344625_cfv");

$result = mysqli_query($con,"SELECT * FROM cfv_businfofull WHERE busnumber = 1 ");

echo "<table border='1'>
<tr>
<th>Bus Number</th>
<th>StopNames</th>
<th>Time</th>
<th>Day Of Week </th>
</tr>";

while($row = mysqli_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['BusNumber'] . "</td>";
  echo "<td>" . $row['StopNames'] . "</td>";
  echo "<td>" . $row['Timings'] . "</td>";
  echo "<td>" . $row['DayOfWeek'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysqli_close($con);

?>

【问题讨论】:

  • 我尝试将 dataType 更改为 jsoup 和 json ,但没有成功?
  • 除非您在服务器上启用跨域 (CORS) 支持,否则您必须切换到 JSONP 并更改您的服务器以支持 JSONP 使用的回调并将结果打包到该回调中。跨度>

标签: php jquery


【解决方案1】:

你应该看看CORS

在您的情况下,您可以在服务器端添加带有响应的 Access-Control-Allow-Origin: * 标头。请注意,您应该只使用受信任的域,而不是 *

【讨论】:

  • 您好 Castt 感谢您将 Access-Control-Allow-Origin: * 添加到我的 php 文件的响应,但就像您说的那样,我需要放置受信任的域而不是 *。这对我的应用程序将如何工作,因为我要将我的 html 文件转换为适用于 Android 应用程序的 .apk,然后将其分发到市场上?
  • 这应该不是问题,只要您在标头中仅指定您信任的服务器即可。这样,您的应用程序将非常安全,并且可以防止 XSS 注入。如上所述,您也可以考虑使用 JSONP。
猜你喜欢
  • 2011-04-10
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 2013-07-28
  • 2013-08-25
  • 2012-01-11
相关资源
最近更新 更多