我正在研究我的大学项目,因为我有一个应该显示城市和温度的网页,我正在尝试使用AJAX在某些时间间隔更新温度。 这是代码
对于ajax请求Java脚本,我在这个答案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可能是一些愚蠢的错误,如果指出会很棒。
答案 0 :(得分:0)
请查看以下代码并更正
[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.
}
}?>