Php 为什么不向 Jquery ajax 发送响应?

问题描述 投票:0回答:1

我想从 mysql 数据库获取数据而不刷新页面。我在客户端使用jquery ajax,在服务器端使用php。请求已发送,但响应为空(如果我在 Firefox 中转到 xhr,则请求很好,没问题,但当我单击应答/响应时,它是空的,请求的大小也是 0)。没有任何错误,但什么也没发生。 这是我的 script.js javascript 文件:

 $(document).ready(function(){
    $.post("ajax.php",
    {
        task: "get_iron"
    },
    function(data)
    {
        $("#iron").html(data);
    }
    );
    console.log("js doesn't have any problem");//it works fine
});

这是我的 ajax.php 文件:

<?php
$method = $_SERVER['REQUEST_METHOD'];
if(strtolower($method)=='post')
{
    if(isset($_POST['task']) && $_POST['task'] == "get_iron")
    {
        $con = mysql_connect('myhost','myusername','mypassword');
        if (!$con) {
          die('Could not connect: ' . mysql_error($con));
        }
        $sql="SELECT iron FROM minerals WHERE username = 'username'";
        $result = mysql_query($sql,$con);
        $row = mysql_fetch_object($result);
        echo json_encode($row);
    }
}

?>

我应该使用 $.ajax 而不是 $.post 吗? 请帮助我并注意我是初学者。 谢谢您的回复。

javascript php jquery mysql ajax
1个回答
1
投票
if(isset($_POST['task']) && $_POST['task' == "get_iron"])

这总是会返回 false,因为你没有名为

'task' == "get_iron"
的 post 字段,并且由于没有 else 语句,所以它不会执行任何操作。

if(isset($_POST['task']) && $_POST['task'] == "get_iron")

这就是你想要的。

© www.soinside.com 2019 - 2024. All rights reserved.