【发布时间】:2017-03-07 11:47:54
【问题描述】:
我有以下 Ajax 调用方法和 asp.net webmethod。
我的 asp.net 函数正在返回一些值,我在 Ajax 调用中需要这些值..
我尝试了很多东西,但还没有成功。
AJAX 调用
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the control.
$("#<%=ddlEmailTemplate.ClientID%>").change(function () {
debugger;
var myparam = $("#<%=ddlEmailTemplate.ClientID%>").val(); //id name for dropdown list
$.ajax({
type: "POST",
url: "FileTax.aspx/ddlEmailTemplate_SelectedIndexChanged",
data: '{param:"' + myparam + '"}',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d)
}
});
});
});
</script>
WebMethod asp.net
在您回答后更新
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public static string ddlEmailTemplate_SelectedIndexChanged(string param)
{
string subject;
string Description;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ForMyTaxConnectionString"].ConnectionString))
{
con.Open();
DataSet ds = new DataSet();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Spo_ShowEmailTemplateContent";
cmd.Parameters.Add(new SqlParameter("@Tid", SqlDbType.Int)).Value = Convert.ToInt32(param);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
con.Close();
da.Dispose();
}
if (ds.Tables[0].Rows.Count > 0)
{
DataRow dr = ds.Tables[0].Rows[0];
subject = Convert.ToString(dr["TemplateSubject"]);
Description = Convert.ToString(dr["TemplateDescription"]);
}
}
}
return JsonConvert.SerializeObject(new { subject = subject, description = Description });
// return subject ;
【问题讨论】:
-
你有没有在成功函数中检查过哪些数据提供了
alert(data); -
@RonyLoud 我无法从 webmethod 返回一些东西,所以成功是空的
-
您需要提供
dataType:'JSON',因为您希望数据中有json,并检查alert(data.subject) -
但是我怎样才能在这里返回主题的值呢?这就是问题
-
JsonConvert.SerializeObject(new { subject = subject, description = Description })在这里您将 Class 作为 Json 对象发送,该对象在数据中接收