How to send 'data' to ASMX web service via AJAX POST?

后端 未结 3 1266
滥情空心
滥情空心 2021-02-04 22:27

I can successfully receive values from my web service so in that repect the script is working fine. However I am now trying to send data to the webservice using the \'data\' fie

相关标签:
3条回答
  • 2021-02-04 22:47

    data: "{"parameterName": "test"}"

    in WebService: public void GetData(string parameterName) {}

    0 讨论(0)
  • 2021-02-04 22:49

    jQuery takes the data argument and converts it into the appropriate type of request variables.

    So you use something like:

    data: { myParameterName: "myParameterValue", myParameterName2: "myParameterValue2" }
    

    and jQuery does the rest of the work for you.

    A specific example based on a comment:

    data: { toSend: "test" }
    
    0 讨论(0)
  • 2021-02-04 23:00

    For asmx you need to pass a stringified version of the data object, so for example:

    var data = "{param1:" + param1IsANumber +
               ", param2:\"" + param2IsAString + "\"}";
    $.ajax({
     data: data,
     dataType: "json",
     url: url,
     type: "POST",
     contentType: "application/json; charset=utf-8",
     success: function (result) {}
    });
    

    Or you can hava an object and use jquery-json

    var data = {};
    data.param1 = 1;
    data.param2 = "some string";
    $.ajax({
     data: jQuery.toJSON(data),
     dataType: "json",
     url: url,
     type: "POST",
     contentType: "application/json; charset=utf-8",
     success: function (result) {}
    });
    

    Finally, your web service class must look like:

    [WebService(Namespace = "http://www.somedomainname.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class MyService : System.Web.Services.WebService
    {
      [WebMethod]
      [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
      public void MyServiceCall(int param1, string param2)
      {
      }
    }
    
    0 讨论(0)
提交回复
热议问题