C# 如何使用 JQuery Ajax 调用从 Web 方法发送和检索数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17655807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:07:10  来源:igfitidea点击:

How to send and retrieve data from web method using JQuery Ajax Call?

c#javascriptjqueryasp.netajax

提问by SamuraiHyman

I have a text box and a button next to it. I want to send the content of textbox through Jquery ajax call to webmethod and get back the upper case value of the same and display that in alert. So far i have this code but its not working.

我有一个文本框,旁边有一个按钮。我想通过 Jquery ajax 调用将文本框的内容发送到 webmethod 并取回相同的大写值并将其显示在警报中。到目前为止,我有这段代码,但它不起作用。

JAVASCRIPT:

爪哇脚本:

function CallWM()
    {          

        var name = $('#name').val();         


        RealCallWM(name);


    }
    function RealCallWM(name) {

        $.ajax({
            url: 'Register.aspx/UpperWM',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: { name: JSON.stringify(name) },
            success: OnSuccess(response),
            error: function (response) {
                alert(response.responseText);
            }
        })
    };

HTML:

HTML:

  Name:    <input id="name" type="text" /> 
<input id="Button1" type="button" value="button" onclick="CallWM();"/></div>
    </form>

WEB METHOD:

网络方法:

 [WebMethod]
        public static string UpperWM(string name )
        {
            var msg=name.ToUpper();
            return (msg);
        }

采纳答案by Able Alias

As per your comment I understood your issue not yet resolved, so just try this

根据您的评论,我了解您的问题尚未解决,所以试试这个

    function RealCallWM(name) {
        $.ajax({
            type: "POST",
            url: "Default.aspx/UpperWM",
            data: JSON.stringify({ name: $('#name').val() }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            success: function (data, status) {
                console.log("CallWM");
                alert(data.d);
            },               
            failure: function (data) {
                alert(data.d);
            },
            error: function (data) {
                alert(data.d);
            }
        });
    }

回答by Darin Dimitrov

Replace:

代替:

data: '{name: ' + name + '}',

with:

和:

data: { name: JSON.stringify(name) },

to ensure proper encoding. Right now you are sending the following payload:

以确保正确编码。现在您正在发送以下有效负载:

{name:'some value'}

which is obviously an invalid JSON payload. In JSON everything should be double quoted:

这显然是一个无效的 JSON 有效负载。在 JSON 中,一切都应该用双引号引起来:

{"name":"some value"}

That's the reason why you should absolutely never be building JSON manually with some string concatenations but using the built-in methods for that (JSON.stringify).

这就是为什么您绝对不应该使用某些字符串连接手动构建 JSON,而是使用内置方法 ( JSON.stringify) 的原因。

Side note: I am not sure that there's a callback called failurethat the $.ajaxmethod understands. So:

旁注:我不确定是否有调用failure$.ajax方法理解的回调。所以:

$.ajax({
    url: 'Register.aspx/UpperWM',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: { name: JSON.stringify(name) },
    success: OnSuccess(response),
    error: function (response) {                        
        alert(response.responseText);
    }
});

Also notice that in your error callback I have removed the response.dproperty as if there's an exception in your web method chances are that the server won't return any JSON at all.

另请注意,在您的错误回调中,我删除了该response.d属性,就好像您的 Web 方法中存在异常一样,服务器根本不会返回任何 JSON。