You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP+CURL+AJAX邮编信息下拉查询功能故障求助

问题描述

我在IT领域相关经验有限,现在要实现一个基于AJAX、PHP和CURL的下拉列表功能,从指定API获取国家邮编信息。目前PHP代码里的for循环无法正确遍历API返回的数据,也没法根据下拉选择返回对应结果,附上我的代码,求技术帮助。
API地址:http://api.geonames.org/postalCodeCountryInfoJSON?formatted=true&&username=mlord&style=full


PHP代码

<?php

    ini_set('display_errors', 'On');
    error_reporting(E_ALL);

    $executionStartTime = microtime(true);

    $url = 'http://api.geonames.org/postalCodeCountryInfoJSON?formatted=true&&username=mlord&style=full' . '&countryName=' . $_REQUEST['countryName'] . '&username=mlord&style=full';
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);

    $result=curl_exec($ch);

    curl_close($ch);

    $decode = json_decode($result,true);    
    
    $country = null;
    

for($i = 0; $i < count($decode["geonames"]); $i++){

                if($_REQUEST["countryName"] == $decode["geonames"][$i]["countryCode"]){

                                $country = $decode["geonames"][$i];

}

}

    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "success";
    $output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
    $output['data'] = $decode['geonames'];
    
     
    header('Content-Type: application/json; charset=UTF-8');

    echo json_encode($output); 
    

?>

JS脚本

$('#btnRun').click(function() {

        $.ajax({
            url: "php/getPostalCodeInfo.php",
            type: 'POST',
            dataType: 'json',
            data: {
                countryName: $('#countryName').val(),
                
            },
            success: function(result) {

                console.log(JSON.stringify(result));

                if (result.status.name == "ok") {

                    $('#txtcountryCode').html(result['data'][0]['countryCode']);
                    $('#txtcountryName').html(result['data'][0]['countryName']);
                    $('#txtnumPostalCodes').html(result['data'][0]['numPostalCodes']);
                    $('#txtminPostalCode').html(result['data'][0]['minPostalCode']);
                    $('#txtmaxPostalCode').html(result['data'][0]['maxPostalCode']);

                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                // your error code
            }
        }); 
    });

HTML代码

<!doctype html>

<html lang="en">

    <head>

        <meta charset="utf-8">
        <title>Task</title>
        <meta name="description" content="Task">

    </head>
    <body>

        <select id="countryName">
            <option value="AD">Andorra</option>
            <option value="AR">Argentina</option>
            <option value="AT">Austria</option>
            <option value="AU">Australia</option>
        </select>

        <button id="btnRun">Run</button>

        <br><br>

        <div id="divResults">
            
            <table>
                <tr>
                    <td align="right">
                        Country Code: 
                    </td>
                    <td id="txtcountryCode">
                        
                    </td>

                </tr>
                
                <tr>
                    <td align="right">
                        Country Name: 
                    </td>
                    <td id="txtcountryName">
                        
                    </td>

                </tr>

                <tr>
                    <td align="right">
                        Number of Postal Codes: 
                    </td>
                    <td id="txtnumPostalCodes">
                        
                    </td>

                </tr>

                <tr>
                    <td align="right">
                        Minimum Postal Code: 
                    </td>
                    <td id="txtminPostalCode">
                        
                    </td>

                </tr>

                <tr>
                    <td align="right">
                        Maximum Postal Code: 
                    </td>
                    <td id="txtmaxPostalCode">
                        
                    </td>

                </tr>

                
            </table>

        </div>

        <script type="application/javascript" src="js/jquery-2.2.3.min.js"></script>
        <script type="application/javascript" src="js/script.js"></script>

    </body>

</html>

问题分析与修复方案

核心问题点

  1. API参数错误:拼接URL时重复添加username和style参数,且用countryName传递国家代码,不符合API要求(实际需用country参数匹配国家代码)。
  2. 遍历逻辑无效:找到匹配的国家数据后,未将筛选结果返回前端,仍返回整个geonames数组。
  3. 前端取值错误:直接取数组第一个元素,未根据选择的国家代码匹配对应数据。

修复后的PHP代码

<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);

$executionStartTime = microtime(true);

// 修正API参数,避免重复字段,用country传递国家代码
$url = 'http://api.geonames.org/postalCodeCountryInfoJSON?formatted=true&username=mlord&style=full';
if (!empty($_REQUEST['countryCode'])) {
    $url .= '&country=' . $_REQUEST['countryCode'];
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);

$result = curl_exec($ch);
curl_close($ch);

$decode = json_decode($result, true);    
$countryData = [];

// 处理返回数据,筛选目标国家信息
if (!empty($decode["geonames"])) {
    if (!empty($_REQUEST['countryCode'])) {
        foreach ($decode["geonames"] as $item) {
            if ($_REQUEST["countryCode"] == $item["countryCode"]) {
                $countryData = $item;
                break; // 找到匹配项后终止循环,提升效率
            }
        }
    } else {
        $countryData = $decode["geonames"];
    }
}

$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
$output['data'] = $countryData;

header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output); 
?>

修复后的JS脚本

$('#btnRun').click(function() {
    $.ajax({
        url: "php/getPostalCodeInfo.php",
        type: 'POST',
        dataType: 'json',
        data: {
            countryCode: $('#countryName').val(), // 参数名与PHP端统一
        },
        success: function(result) {
            console.log(JSON.stringify(result));
            if (result.status.name == "ok") {
                // 直接使用筛选后的单条数据
                $('#txtcountryCode').html(result.data.countryCode);
                $('#txtcountryName').html(result.data.countryName);
                $('#txtnumPostalCodes').html(result.data.numPostalCodes);
                $('#txtminPostalCode').html(result.data.minPostalCode);
                $('#txtmaxPostalCode').html(result.data.maxPostalCode);
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error('请求失败:', textStatus, errorThrown);
        }
    }); 
});

修复说明

  1. API参数修正:使用country参数传递国家代码,移除重复请求参数,符合API规范。
  2. PHP逻辑优化:遍历找到匹配数据后,将单条结果返回前端,添加break提升遍历效率。
  3. 前端逻辑调整:参数名与PHP端统一,回调中直接使用筛选后的单条数据,不再取数组第一个元素。

内容的提问来源于stack exchange,提问作者Megan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 02:30:47