如何通过AJAX POST“数据”发送到ASMX Web服务?发送到、数据、POST、AJAX

2023-09-11 00:52:33 作者:女人的成就不是因为男人,

我可以成功地接收从我的Web服务值,以便在repect脚本工作正常。但是我现在想将数据发送到使用下面的数据字段中的Web服务。我无法弄清楚是如何发送一个简单的字符串(如测试)到Web服务,这是我的web方法需要作为一个参数。

任何帮助是非常AP preciated。例如:

 函数setQuestion(){
$阿贾克斯({
    键入:POST,
    **数据:{},** //我如何使用它来发送一个字符串?
    数据类型:JSON,
    网址:HTTP:// someURL
    的contentType:应用/ JSON的;字符集= UTF-8,
    成功:的onSuccess
});
}

功能的onSuccess(MSG){
$(#questiontxt)追加(MSG);
}
 

解决方案

有关ASMX你需要传递的数据对象的字符串化的版本,因此,例如:

  VAR数据={参数1:+ param1IsANumber +
           ,参数2:\+ param2IsAString +\};
$阿贾克斯({
 数据:数据,
 数据类型:JSON,
 网址:网址,
 键入:POST,
 的contentType:应用/ JSON的;字符集= UTF-8,
 成功:函数(结果){}
});
 
的使用,ajax调用 的使用,webservice web服务 asmx的使用,ajax调用 进行json传输

或者你也可以哈瓦一个对象,并使用 jQuery的JSON的

  VAR数据= {};
data.param1 = 1;
data.param2 =一些字符串;
$阿贾克斯({
 数据:jQuery.toJSON(数据),
 数据类型:JSON,
 网址:网址,
 键入:POST,
 的contentType:应用/ JSON的;字符集= UTF-8,
 成功:函数(结果){}
});
 

最后,您的Web服务类必须是这样的:

  [WebService的(命名空间=htt​​p://www.somedomainname.com/)
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)
[ScriptService]
公共类为MyService:System.Web.Services.WebService
{
  [WebMethod的]
  [ScriptMethod(ResponseFormat = ResponseFormat.Json)
  公共无效MyServiceCall(INT参数1,字符串参数2)
  {
  }
}
 

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' field below. What i cant figure out is how to send a simple string (e.g. "test") to the web service which is what my web method expects as a parameter.

Any help is much appreciated. For example:

function setQuestion() {
$.ajax({
    type: "POST",
    **data: "{}",** //how do i use this to send a string??
    dataType: "json",
    url: "http://someURL",
    contentType: "application/json; charset=utf-8",
    success: onSuccess
});
}

function onSuccess(msg) {
$("#questiontxt").append(msg);
}

解决方案

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)
  {
  }
}

 
精彩推荐