为什么php ajax不给任何响应


Why php ajax is not giving any response?

我正在做我的大学项目,在这个项目中,我有一个网页,应该显示城市和温度,我试图使用AJAX每隔一段时间更新温度。下面是代码

用于ajax请求Java Script,我在这个答案中看到了这个代码https://stackoverflow.com/a/18243161/4341530

function postAjaxRequest(qry){
alert("Ajax response on " +qry);
$.ajax({
type: "POST",
url: "ajax_resp.php",
data: {q: qry},
dataType:'JSON', 
success: function(response){
    dispatchCallBack(qry,response);
}});}

alert("Ajax response on " +qry);工作正常,所以我知道这段代码正在运行。但是,当我把这种"alert()"放在dispatchCallBack(qry,response);之前时,它不工作,所以我在这里推断请求不成功。

这里是ajax_resp.php

<?php
if(isset($_POST['q'])&&!empty($_POST['q'])
{
    if($_POST['q']=="c_temp")
    {
        $api_key = "Here's my api key, working alright"; 
        $city_id = "here's city id, also working correct";
        $url = "http://api.openweathermap.org/data/2.5/forecast/city?id=".$city_id."&APPID=".$api_key;
        $json = file_get_contents($url);
        $json_o = json_decode($json);
        $city_name =  $json_o->city->name;
        $temp_c =  $json_o->list[0]->main->temp-273;
        echo json_encode(array("city"=>$city_name,"temp"=>$temp));
//I have checked JSON response seperately its correct. I was able to get city name and temperature variable properly initialised.
    }
}?>

所以我不知道怎么了。我是新手:p可能是一些愚蠢的错误,如果指出来就太好了。

请查看下面的代码并改正

[1]使用单引号或双引号从具有字符串索引

$_POST变量中获取数据

[2] $qry之前没有定义。读取问题后,$qry的最可能值可以是$_POST['q']。因此,将$qry替换为$_POST['q']或分配$qry = $_POST['q']

if(isset($_POST['q'])&&!empty($_POST['q'])
{
if($_POST['q']=="c_temp") <==  $_POST['q'] instead of $qry
{
    $api_key = "Here's my api key, working alright"; 
    $city_id = "here's city id, also working correct";
    $url = "http://api.openweathermap.org/data/2.5/forecast/city?id=".$city_id."&APPID=".$api_key;
    $json = file_get_contents($url);
    $json_o = json_decode($json);
    $city_name =  $json_o->city->name;
    $temp_c =  $json_o->list[0]->main->temp-273;
    echo json_encode(array("city"=>$city_name,"temp"=>$temp));
    //I have checked JSON response seperately its correct. I was able to get city name and temperature variable properly initialised.
}
}?>