gpt4 book ai didi

javascript - C# Web 方法未在 javascript 中调用

转载 作者:行者123 更新时间:2023-11-28 11:09:32 25 4
gpt4 key购买 nike

enter image description here我创建了一个 Web 方法,现在我在 java 脚本文件中调用它,但它给出了路径错误,它无法找到我给出的路径..

Web 方法代码为:

    [System.Web.Services.WebMethod]
public static int ItemCount(string itemId)
{
int val = 0;

Item itm = Sitecore.Context.Database.GetItem(itemId);
val = itm.Children.Count;

return val;
}

java脚本函数调用如下:

    function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Views/GetItem.aspx/ItemCount",
data: { itemId: itemId },
dataType: "json",
async: false,
success: function (data) {
funRes = data.result;
},
error: function(err) {
alert(err.responseText);
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;}

虽然我给出了 C# 方法类的确切路径,但它不起作用,在控制台上给出了错误,任何人都可以建议我在这里缺少什么..

最佳答案

ajax 与 asp.net 配合使用的规则很少。

  • Your WebMethod should be public and static.
  • If your WebMethod expects some parameter(s) than these parameter(s) must be passed as data in ajax.
  • Name of parameter(s) should be same in WebMethod and in data part of ajax.
  • Data passed from ajax should be in json string.For this you can use JSON.stringify or you will have to surround the values of parameter(s) in quotes.

请检查下面的 ajax 调用示例

function CallAjax()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/CallAjax",
data: JSON.stringify({ name: "Mairaj", value: "12" }),
dataType: "json",
async: false,
success: function (data) {
//your code

},
error: function (err) {
alert(err.responseText);
}

});
}



[WebMethod]
public static List<string> CallAjax(string name,int value)
{
List<string> list = new List<string>();
try
{
list.Add("Mairaj");
list.Add("Ahmad");
list.Add("Minhas");
}

catch (Exception ex)
{

}

return list;
}

编辑

如果您在 ajax 中使用 GET,则需要启用从 GET 请求调用您的 webmethod。在 WebMetod 之上添加 [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static int ItemCount()

关于javascript - C# Web 方法未在 javascript 中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27917255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com