2012-01-25 47 views
1

我使PHP的一個簡單的腳本,它使用AJAX通過郵政編碼獲取城市名 我的Java代碼「xmlResult.Result是未定義」錯誤

<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 

任何解決方案一個錯誤?

+0

alert/console.log前面的'xmlResult'行上... im很確定這將幫助你解決你的問題.. – ManseUK

+0

「Alert/console.log xmlResult on line before」這個解決方案不起作用 –

+0

如果不是爲了提供解決方案 - 它的意思是幫助你......我建議你看看一個名爲[firebug ](http://getfirebug.com/)... – ManseUK

回答

0

你的第一個問題是,foreach塊之前聲明的變量$City心不是 - 所以你會得到有錯誤...

<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/JSON