Ajax调用的前提(以aspx文件为例:)
1、首先需要在aspx文件后台中引用using System.Web.Services;
2、需要调用的方法必须是公共的(public)、静态的(static);如果不是会提示“500 Internal Server Error 问题”,代表找不到method。
3、方法定义需要加入[WebMethod]的声明
4、一般建议由返回类型,最起码可能知道调用成功不成功。
下面是简单的调用示例:
后台方法
[WebMethod]public static string WriteLog(DateTime StartTime, DateTime EndTime)
{ ????if (true) ????{ ??????return ""; ????} ????else ????{ ??????return "读取出错!"; ????} ????return "";}
前台调用
$.ajax({ ???????????????url: ‘Index.aspx/WriteLog‘, ???????????????type: ‘post‘, ???????????????data: JSON2.stringify({ StartTime: $(‘#dtbStartTime‘).datetimebox("getValue"), EndTime: $(‘#dtbEndTime‘).datetimebox("getValue")}), ???????????????cache: false, dataType: ‘json‘, ???????????????contentType: "application/json;charset=utf-8", ???????????????success: function (data) { ???????????????????console.info(data); ???????????????} ???????????});
注意前台调用时必须把json对象转为json字符串,否则会报错 “
无效的 JSON 基元: Types
”
asp.net Ajax调用Aspx后台方法
原文地址:https://www.cnblogs.com/xiaoruilin/p/9110179.html