我寫了個webservices的方法~通過城市名擷取天氣
我如果直解在伺服器端調用不會出現亂碼問題~(我javascirpt是下了微軟的webservices.htc)
可我在javascript調用webservices中文參數變成????,我也試過很多辦法多沒用包括在web,config定義utf-8什麼的也沒用~我現在把代碼發出來,希望大家幫忙
[WebMethod]
public string GetWeather(string city)
{
string weacherhtml = String.Empty;
//轉換輸入參數的編碼類別型
string mycity = System.Web.HttpUtility.UrlEncode(city, System.Text.UnicodeEncoding.GetEncoding("GB2312"));
//初始化新的 WebRequest
HttpWebRequest webrt = (HttpWebRequest)WebRequest.Create("http://php.weather.sina.com.cn/search.php?city=" + mycity);
//返回對 Internet 請求的響應。
HttpWebResponse webrs = (HttpWebResponse)webrt.GetResponse();
//從 Internet 資源返回資料流。
Stream stream = webrs.GetResponseStream();
//讀取資料流
StreamReader srm = new StreamReader(stream, System.Text.Encoding.Default);
//從頭讀到尾,把資料讀到weacherhtml中
weacherhtml = srm.ReadToEnd();
//關閉開啟的資源
srm.Close();
stream.Close();
webrs.Close();
//針對不同的網站,以下開始部分和結束部分不同。
//可通過查看網站的源檔案解決。
int start = weacherhtml.IndexOf("<!-- 天氣狀況 begin -->");
int end = weacherhtml.IndexOf("<!-- 天氣狀況 end -->");
//返回一個HTML的Table,預報城市天氣
return weacherhtml.Substring(start, end - start);
}
javascript
<script language="javascript" type="text/javascript">
var iCallID=0;
function init()
{
service.useService("http://localhost:4897/WebServices/luca.asmx?WSDL","MYPath");
var drp=document.getElementById("<%=DropDownList1.ClientID %>").value;
iCallID=service.MYPath.callService(onResult,"GetWeather",drp);
}
function onResult(result)
{
if(!result.error)
{
divResult.innerText=result.value;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>無標題頁</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="service" style="BEHAVIOR:url(webservice.htc)">
<div style="text-align: left">
<table>
<tr>
<td style="width: 100px">
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="北京">北京</asp:ListItem>
<asp:ListItem Value="上海">上海</asp:ListItem>
</asp:DropDownList></td>
<td style="width: 100px">
<input id="Button1" type="button" value="查詢" onclick="init()" /></td>
</tr>
<tr>
<td colspan="2">
<div id="divResult" style="width:200px; height:300px; overflow:auto">
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
</form>
</body>
</html>