简体   繁体   English

发送JSON到webmethod?

[英]Send JSON to webmethod?

如何使用jQuery将JSON对象发送到Web方法?

Please refer to this article by Dave Ward. 请参阅Dave Ward的这篇文章。 It is a complete tutorial on doing this stuff. 这是完成此操作的完整教程。 Also you will find there other great jquery/ASP.net stuff. 此外,您还会发现其他很棒的jquery / ASP.net东西。

EDIT:- Dave is calling method without any arguments, you can replace empty data property with actual data you want to send: 编辑:-Dave正在调用不带任何参数的方法,您可以将空数据属性替换为要发送的实际数据:

$.ajax({
  type: "POST",
  url: "Default.aspx/GetDate",
  data: "{'name':'tiger1','hobbies':['reading','music']}",//PUT DATA HERE
  contentType: "application/json; charset=utf-8",
  dataType: "json",

WebMethods expect a string containing JSON that will be parsed on the server-side, I use the JSON.stringify function to convert a parameters object to string, and send the data, I have a function like this: WebMethods期望一个包含JSON的字符串将在服务器端进行解析,我使用JSON.stringify函数将参数对象转换为字符串,然后发送数据,我有一个类似这样的函数:

jQuery.executePageMethod = function(location, methodName, methodArguments,
                                    onSuccess, onFail) {
    this.ajax({
        type: "POST",
        url: location + "/" + methodName,
        data: JSON.stringify(methodArguments), // convert the arguments to string
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data, status) {
            var jsonData = JSON.parse(data.d);
            onSuccess(jsonData, status);
        },
        fail: onFail
    });
};

I recommend you to include the json2.js parser in your pages, to have the JSON.stringify function cross-browser available. 我建议您在页面中包含json2.js解析器,以使JSON.stringify函数可以跨浏览器使用。

Another library you can use is the jquery-json library . 您可以使用的另一个库是jquery-json Once included: 一旦包含:

var json = $.toJSON(your_object);

The most convenient solutions I've seen simplify this by using the open-source JSON2.js library to parse and 'stringify' complex object data. 我看到的最方便的解决方案通过使用开源JSON2.js库来解析和“字符串化”复杂的对象数据来简化此过程。

These two excellent articles go into detail: 这两篇出色的文章进行了详细介绍:

The second article might be especially relevant for you, though it calls a web service method with the following signature ... 第二篇文章可能与您特别相关,尽管它使用以下签名调用了Web 服务方法...

 public void SendValues(List<string> list) 

... it demonstrates how to use the JSON2.js library to render a List<string> in javascript (using jQuery, this example is taken directly from the second article): ...它演示了如何使用JSON2.js库在javascript中呈现List<string> (使用jQuery,此示例直接摘自第二篇文章):

 var list = ["a", "b", "c", "d"]; var jsonText = JSON.stringify({ list: list }); // The 'list' is posted like this $.ajax({ type: "POST", url: "WebService1.asmx/SendValues", data: jsonText, contentType: "application/json; charset=utf-8", dataType: "json", success: function() { alert("it worked"); }, failure: function() { alert("Uh oh"); } }); 

Just use your webmethod URL in lieu of the web service's. 只需使用您的web方法URL来代替Web服务。

You'd need to post it using Ajax and accept the incoming string on the webmethod. 您需要使用Ajax发布它,并在webmethod上接受传入的字符串。 Then you'd need to use the JavaScript deserializer to convert it into an object on the server side. 然后,您需要使用JavaScript反序列化器将其转换为服务器端的对象。

Sample code is here: 示例代码在这里:

var dataString = JSON.stringify({
                            contractName: contractName,
                            contractNumber: contractNumber
                        });

                        $.ajax({
                            type: "POST",
                            url: "CreateQuote.aspx/GetCallHistory",
                            data: dataString,
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (result) {
                                alert(result.CallHistoryDescription);
                                    OpenLightBox('divDelete');

                            }
                        });


        [System.Web.Services.WebMethod]
        public static object GetCallHistory(string contractName, string contractNumber)
        {
            return new
            {
                CallHistoryDescription = "Nalan"
            };

        }

JSON.stringify does help, but: JSON.stringify确实有帮助,但是:

  1. it's not cross-browser take a look here: http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/# 它不是跨浏览器,请在这里查看: http : //www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/#

  2. For browser in-built functions - every browser will have its problems. 对于浏览器的内置功能-每个浏览器都会有问题。 If You use the above serialization You will need to: 如果使用上述序列化,则需要:

    • remove newlines with regexp in strings 用字符串中的regexp删除换行符
    • take care about " in strings 注意字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM