douzhang7184 2016-06-17 14:53
浏览 64
已采纳

mysql查询不能与ajax中的跨域一起使用

my problem is the following... I made some php code that reads records from a mysql database:

$host = $_SESSION['host'];
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$db = $_SESSION['db'];

$con = mysqli_connect($host,$username,$password,$db);

$sql = "SELECT * FROM `table`";
$result = $con->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
         ...
    }
}

my html:

<button onclick="list">submit</button>
<div id="output"></div>

<script>
var thisHost = "host.php";
function list() {
    $.ajax({
        type: 'POST',
        url: thisHost,
        data: "list=true",
        success: function(data) 
        {
            $("#output").html(data);
        },
        error: function (responseData, textStatus, errorThrown) 
        {
            console.warn(responseData, textStatus, errorThrown);
        }
    });
}
</script>

as far as that everything is working fine. However now i want to call the php code from another host. Therefor the html file is on the other host (localhost:81) and the php file stays on the old host (localhost:80).

now I noticed that i need a something to cross the domain because ajax doesn't seem to work with other hosts. So all i did was adding these lines to the php code right at the beginning:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');

and change the value of the thisHost var in javascript to

"http://localhost:80/host.php"

after that the ajax part works again and the php response. However every time i want to make a query by doing something like this:

$sql = "SELECT * FROM `table`";

i will get this error:

Fatal error: Uncaught Error: Call to a member function query() on null in C:\path\to\host.php:71 Stack trace: #0 {main} thrown in C:\path\to\host.php on line 71

i'm pretty sure that the query is correct. So what do i need to change?

  • 写回答

1条回答 默认 最新

  • dougangxin5695 2016-06-17 15:05
    关注

    Calling a method on an invalid handle will produce errors like this. Always check that your connection request succeeded and handle any errors that could have occurred.

    Turning on mysqli exceptions makes these things a lot harder to ignore.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line