";xmlResult.Result未定义”;错误


"xmlResult.Result is undefined" error

我制作了一个简单的php脚本,使用ajax通过邮政编码获取城市名称我的java代码是

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://jquery-xml2json-plugin.googlecode.com/svn/trunk/jquery.xml2json.js"></script>
        <script type="text/javascript">
        $(document).ready(function(){
            var initialPostal;
            $('#postal').bind('keyup change',function(e) {
            if(($("#postal").val().length==3 || $("#postal").val().length==6 || $("#postal").val().length==7) && $("#postal").val()!=initialPostal)
                { 
                              initialPostal=$("#postal").val();
                        $.get('citylookup.php?postal='+$("#postal").val(), function(xml){
                        var xmlResult = $.xml2json(xml);
                            $("#city").val(xmlResult.Result.City);
                            alert(xmlResult.Result.City);
                        }); } });   });  </script>

//这是我的html代码

<form id="form1" name="form1" method="post" action="">
  <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td>Postal:</td>
      <td><input type="text" name="postal" id="postal" /></td>
    </tr>
    <tr>
      <td>City:</td>
      <td><input type="text" name="city" id="city" /></td>
    </tr>
  </table>

我的citylookup.php页面代码是hear

<?php
$url = 'http://where.yahooapis.com/geocode?q='.$_GET['postal'].'&country=india';
$xml = simplexml_load_file($url);
foreach($xml as $result)
{
    if($result->postal==$_GET['postal'])
    {
    $City = $result->city;
    }
}
echo $City;
?>

它给我一个类似的错误

Error: xmlResult.Result is undefined
Source File: http://localhost/postalcode/citylookup.html
Line: 17

有什么解决方案吗?

您的第一个问题是$City变量没有在foreach块之前声明,所以您会在那里得到一个错误。。。

<br /> <b>Notice</b>:  
Undefined variable: City in <b>citylookup.php</b> on line <b>14</b><br />

尝试:

<?php
$url = 'http://where.yahooapis.com/geocode?q='.$_GET['postal'].'&country=india';
$xml = simplexml_load_file($url);
$City = "";
foreach($xml as $result)
{
    if($result->postal==$_GET['postal'])
    {
    $City = $result->city;
    }
}
echo $City;
?>

您的第二个问题是,JavaScript中没有错误检查——即,如果您键入未知的邮件,您将看到相同的错误——请考虑检查返回值,以确保实际返回了有价值的东西。实际上,您只是使用上面的PHP返回了一个单词。。。不是XML/JON-