php - "xmlResult.Result is undefined"错误

标签 php javascript ajax jquery

我制作了一个简单的 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 页面代码被听到

<?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 block 之前声明 - 所以你会在那里得到一个错误......

<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 中没有错误检查 - 即,如果您输入未知的邮件,您将看到相同的错误 - 考虑检查返回值以确保确实返回了有值(value)的内容。实际上,您只是使用上面的 PHP 返回一个单词......而不是 XML/JSON

关于php - "xmlResult.Result is undefined"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9001670/

相关文章:

php - 加载评论时加入查询

javascript - jquery html(array) 不会插入数组中的所有项目

php - Ajax 返回随机值?

php - 如何用php和mysql计算剩余时间?

php - Laravel 数据库播种器类

php - 将数组内容存入数据库

javascript - 计算 ajax 响应的时间并在 SetTimeout 函数中使用该时间

javascript - 谁能解释为什么第一个例子的返回值是 NaN ?第二个例子很好

javascript - Popper.js 下拉菜单/工具提示的初始位置错误

javascript - Laravel Ajax POST 请求不起作用 : 302 found