我想从free.worldweatheronline.com获取xml数据 我尝试了以下方式: -
<fx:Script>
<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
private var main_xml_url:String = "http://free.worldweatheronline.com/feed/weather.ashx?q="+cityName.text.toString()+"&format=xml&num_of_days=2&key=my_api_key"; // there I put my api key not showing here//
protected function weatherService_resultHandler(event:ResultEvent):void
{
// TODO Auto-generated method stub
var result_weather_data:Object = event.result;
cityNameData.text = data.request.query;
}
protected function weatherService_faultHandler(event:FaultEvent):void
{
// TODO Auto-generated method stub
cityNameData.text = event.message.toString();
}
]]>
</fx:Script>
<fx:Declarations>
<s:HTTPService id="weatherService"
url="main_xml_url"
resultFormat="object"
result="weatherService_resultHandler(event)"
fault="weatherService_faultHandler(event)"/>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:TextInput id="cityName" text="Hyderabad" x="10" y="10" width="219" fontWeight="bold" prompt="Enter city Name"/>
<s:Label id="cityNameData" x="108" y="109" width="202" fontSize="20" fontWeight="bold"/>
但是有一个错误说: 无法访问null对象引用的属性或方法。 在private var main_xml_url:String
请提前解决,请先帮忙。
答案 0 :(得分:0)
上面的代码表示您正在尝试在对象初始化时检索并分配cityName.text.toString()
的值。
作为cityName
的显示对象TextInput
在分配时不会添加到显示中。因此,你正在获得NPE。
您可以按如下方式更正此问题:
<fx:Declarations>
<s:HTTPService id="weatherService"
url="{BASE_URL}"
resultFormat="object"
result="weatherService_resultHandler(event)"
fault="weatherService_faultHandler(event)">
<s:request xmlns="">
<q>{cityName.text.toString()}</q>
<format>{FORMAT}</format>
<num_of_days>{NUMBER_OF_DAYS}</num_of_days>
<key>{API_KEY}</key>
</s:request>
</s:HTTPService>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
private static const BASE_URL:String="http://free.worldweatheronline.com/feed/weather.ashx"
private static const API_KEY:String="your API key here"
private static const NUMBER_OF_DAYS:uint=2;
private static const FORMAT:String="xml";
protected function weatherService_resultHandler(event:ResultEvent):void
{
// TODO Auto-generated method stub
var result_weather_data:Object=event.result;
cityNameData.text=result_weather_data.request.query;
}
protected function weatherService_faultHandler(event:FaultEvent):void
{
// TODO Auto-generated method stub
cityNameData.text=event.message.toString();
}
]]>
</fx:Script>
<s:layout>
<s:VerticalLayout/>
</s:layout>
<s:TextInput id="cityName"
width="219"
text="Hyderabad"
x="10"
y="10"
fontWeight="bold"
prompt="Enter city Name"/>
<s:Label id="cityNameData"
width="202"
x="108"
y="109"
fontSize="20"
fontWeight="bold"/>
<s:Button label="Send" click="{weatherService.send()}"/>
此外,您忘记拨打send()
对象上的weatherService
。
这意味着无论如何都不会触发您的Web服务调用。
有关此问题的更多信息,请查看LiveDocs