我制作了一个简单的 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/