asp.net( C# )中JS调用ashx文件传递中文参数取不到值的解决方案
实现在text中输入数据,areatext里动态搜索
<th class="t_r">
请选择公司:
</th>
<td width="89%" class="kuang1">
<asp:TextBox ID="txtKeyWord" runat="server"></asp:TextBox>
<span class="red">*</span><br />
<select id="txtCompanyList" multiple="multiple" name="D1" onclick="CompanySelect()"
style="width: 380px; height: 119px">
<option></option>
</select>
</td>
JS:
function BindCompanyList() {
var comapyname = $("#txtKeyWord").val();
$("#txtCompanyList").html("");
$.getJSON("GetCompanyList.ashx?companyname=" + escape(comapyname), null, function(json) {
if (json != null) {
$.each(json, function(i) { $("#txtCompanyList").append($("<option></option>").val(json[i].id).html(json[i].companyname)) });
}
});
}
function CompanySelect() {
var Obj = document.getElementById("txtCompanyList");
if (document.getElementById("txtCompanyList").options.length != 0) {
document.getElementById("txtKeyWord").value = Obj.options[Obj.selectedIndex].text;
}
}
ASHX:
public void ProcessRequest(HttpContext context)
{
StringBuilder sb=new StringBuilder();
if (context.Request.Params["companyname"] != null)
{
DataTable dt = null;
string strcompanyname = context.Server.HtmlDecode(context.Request.Params["companyname"].ToString());
if (strcompanyname!="")
{
dt = new BLL.CZL_CompanyInfo().GetList(" companyname like '%" + strcompanyname + "%'").Tables[0];
}
else
{
dt = new BLL.CZL_CompanyInfo().GetAllList().Tables[0];
}
if (dt == null || dt.Rows.Count == 0)
{
return;
}
else
{
sb.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
//返回JOSN数据
sb.Append("{\"id\":\"" + dt.Rows[i]["id"].ToString() + "\",\"companyname\":\"" +Common.ProductAbout.ReturnStr(dt.Rows[i]["companyname"].ToString()) + "\"},");
}
sb.Remove(sb.Length - 1, 1);
sb.Append("]");
}
}
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Write(sb.ToString());
}
注意传递值的时候,js里用escape()对参数进行编码
取得的时候,.cs中用context.Server.HtmlDecode()进行对参数的解密