c# - 当方法有参数时 Ajax 回调失败

标签 c# javascript asp.net ajax

我有以下 JavaScript:

<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: "POST",
            url: "WebForm3.aspx/sayHello",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: "json",
            success: AjaxSucceeded,
            error: AjaxFailed
        }); 
    });
    function AjaxSucceeded(result) {
        alert(result.d);
    }
    function AjaxFailed(result) {
        alert(result.status + ' ' + result.statusText);
    }  
</script>  

我的代码中有以下内容。

[WebMethod]
public static string sayHello() 
{
    return "hello";
}

这有效并显示你好。

现在,如果我这样做:

[WebMethod]
public static string sayHello(string args) 
{
    return "hello";
}

然后我收到内部服务器错误 500 作为回复。

如何更改此设置以允许我将实际数据发送到服务器端?

最佳答案

data: {
    args: "hello world"
},

此外,还删除 contentTypedataType
另外,请添加traditional: true。您的最终请求将是:

$.ajax({
    type: "POST",
    url: "WebForm3.aspx/sayHello",
    traditional: true,
    data: {
        args: "hello world"
    },
    success: AjaxSucceeded,
    error: AjaxFailed
}); 

关于c# - 当方法有参数时 Ajax 回调失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14632932/

相关文章:

c# - 如何使XPath仅在每个表中搜索?

javascript - 如何禁用具有特定 id 模式的 div block ?

javascript - 这个 JavaScript/HTML 有什么问题

javascript - 无法使用 jquery 上传文件

c# - 如何在 asp.net web 表单中基于数据库表中的行动态创建文本框?

c# - 在 asp.net 中创建日期时间选择器

c# - lambda 表达式使用反射吗?

asp.net - ASP.NET Web 部件是实现门户架构的可行技术吗

javascript - 尝试加载 HTML5 输入类型=日期元素的 ASP 文本框

c# - 用 IEnumerable 实现的快速排序的复杂度是多少?