Dotnetnuke - 如何使用 Ajax 在代码后面调用方法
Dotnetnuke - How to call method in code behind with Ajax
这是脚本
<script type="text/jscript">
function ajaxcall(e) {
$.ajax({
type: "POST",
url: "/DesktopModules/Modules/Admin/City/AddCity.ascx/GetMethod",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ value: "Vinay" }),
dataType: "json",
success: function (value) {
alert(value.d);
},
error: function () { alert("Ajax Error"); }
});
};
这是隐藏代码:
[WebMethod]
public static string GetMethod(String value)
{
return value;
}
当我从按钮调用功能时。它显示 js 警报 Ajax Error
<input type="button" id="button" value="Test" onclick="ajaxcall()" />
我试过用 AddCity.ascx/GetMethod
替换 /DesktopModules/Modules/Admin/City/AddCity.ascx/GetMethod
但还是不行!
您不能从 ASCX 用户控件调用 WebMethod - IIS 不允许。它必须在 ASPX 页面中。
如果您不需要任何安全性,您可以创建一个通用处理程序(.ASHX 文件)。
public class CityHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var fn = context.Request.QueryString["action"];
var newCity = context.Request.QueryString["city"];
if (fn == "add")
{
// TODO: add city
}
context.Response.ContentType = "text/plain";
context.Response.Write("OK");
}
public bool IsReusable
{
get { return false; }
}
}
然后更改您的 ajax 代码:
$.ajax({
type: "GET",
url: "/DesktopModules/Modules/Admin/City/CityHandler.ashx?action=add&city=Vinay",
success: function (value) {
alert(value);
},
error: function () { alert("Ajax Error"); }
});
这是脚本
<script type="text/jscript">
function ajaxcall(e) {
$.ajax({
type: "POST",
url: "/DesktopModules/Modules/Admin/City/AddCity.ascx/GetMethod",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ value: "Vinay" }),
dataType: "json",
success: function (value) {
alert(value.d);
},
error: function () { alert("Ajax Error"); }
});
};
这是隐藏代码:
[WebMethod]
public static string GetMethod(String value)
{
return value;
}
当我从按钮调用功能时。它显示 js 警报 Ajax Error
<input type="button" id="button" value="Test" onclick="ajaxcall()" />
我试过用 AddCity.ascx/GetMethod
替换 /DesktopModules/Modules/Admin/City/AddCity.ascx/GetMethod
但还是不行!
您不能从 ASCX 用户控件调用 WebMethod - IIS 不允许。它必须在 ASPX 页面中。
如果您不需要任何安全性,您可以创建一个通用处理程序(.ASHX 文件)。
public class CityHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var fn = context.Request.QueryString["action"];
var newCity = context.Request.QueryString["city"];
if (fn == "add")
{
// TODO: add city
}
context.Response.ContentType = "text/plain";
context.Response.Write("OK");
}
public bool IsReusable
{
get { return false; }
}
}
然后更改您的 ajax 代码:
$.ajax({
type: "GET",
url: "/DesktopModules/Modules/Admin/City/CityHandler.ashx?action=add&city=Vinay",
success: function (value) {
alert(value);
},
error: function () { alert("Ajax Error"); }
});