PHP+JQuery调用Curl API无返回,报Invalid argument错误求助
问题排查与解决步骤
1. PHP代码核心问题:未返回数据给前端
你的PHP脚本仅获取并解析了API数据,但未向前端输出任何内容,这是AJAX接收不到数据的根本原因。同时脚本没有利用前端传递的参数,也未处理curl请求失败的情况。修改后的PHP代码如下:
<?php ini_set('display_errors', 'On'); error_reporting(E_ALL); // 获取前端POST参数,设置默认值避免空值报错 $north = $_POST['north'] ?? '44.1'; $south = $_POST['south'] ?? '-9.9'; $east = $_POST['east'] ?? '-22.4'; $west = $_POST['west'] ?? '55.2'; $username = 'kyleghilotti'; // 拼接带动态参数的API地址 $url = "http://api.geonames.org/weatherJSON?north={$north}&south={$south}&east={$east}&west={$west}&username={$username}"; $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch); // 检查curl请求是否失败 if(curl_errno($ch)){ $error = curl_error($ch); curl_close($ch); header('Content-Type: application/json; charset=UTF-8'); echo json_encode(['error' => $error]); exit; } curl_close($ch); // 解析并输出JSON数据给前端 $decode = json_decode($data, true); header('Content-Type: application/json; charset=UTF-8'); echo json_encode($decode); // 关键:必须输出数据 ?>
2. JS代码的两处优化
- 移除
data对象最后一个键值对的逗号(部分浏览器会因多余逗号解析失败) - 增强错误处理,输出更详细的调试信息;同时修正geonames返回结构的取值路径
修改后的JS代码:
$(window).on('load', function () { if ($('#preloader').length) { $('#preloader').delay(1000).fadeOut('slow', function () { $(this).remove(); }); } }); $('#coordinates').click(function () { $.ajax({ url: "../php/api.php", type: 'POST', dataType: 'json', data: { north: $('#North').val(), south: $('#South').val(), east: $('#East').val(), west: $('#West').val() // 移除末尾多余逗号 }, success: function (result) { console.log(result); // geonames返回的数组键是weatherObservations,不是data if (result && result.weatherObservations && result.weatherObservations.length > 0) { $('#clouds').html(result.weatherObservations[0].clouds); $('#temperature').html(result.weatherObservations[0].temperature); $('#station').html(result.weatherObservations[0].stationName); } else { console.log("无观测数据返回"); } }, error: function (jqXHR, textStatus, errorThrown) { console.log("错误状态:", textStatus); console.log("错误信息:", errorThrown); console.log("PHP返回内容:", jqXHR.responseText); // 查看PHP返回的具体内容 } }); });
3. 关于prepareInjection.js:640:17错误
该错误大概率是因为PHP未返回有效JSON(原脚本无输出),导致JQuery解析JSON失败触发的。修复PHP的输出问题后,此错误会自动消失。
额外注意事项
- 确认前端输入框的ID(
#North、#South等)与HTML中的实际ID一致 - 检查AJAX请求的
url路径是否正确,确保当前页面与api.php的层级关系匹配
内容的提问来源于stack exchange,提问作者Kyle Ghilotti
相关产品推荐
相关产品推荐

