当数据密钥没有数据发送时,即数据:“{}”一个空的
JSON对象,并且Web服务没有参数,以下代码正确执行.我想向webservice发布一些数据,但是我遇到麻烦.
当我尝试将其设置为数据时:“{‘name’:’Niall’,’surname’:’Smith’}”,我收到错误
{"Message":"Invalid web service call,missing value for parameter: \u0027json\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target,IDictionary`2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target,IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context,WebServiceMethodData methodData,IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context,WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
webservice不执行.
这是我的Jquery调用,将我的数据发回服务器.
$.ajax({ type: "POST",url: "/WebServices/BasketServices.asmx/AddItemToBasket",data: "{'name':'niall'}",// Is this Correct?? contentType: "application/json; charset=utf-8",dataType: "json",success: OnItemAddedSuccess }); function OnItemAddedSuccess(result,eventArgs) { //deserialize the JSON and use it to update the Mini Basket var response = JSON.parse(result.d); }
这是我的WebService
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolBoxItem(false)] [System.Web.Script.Services.ScriptService] public class BasketServices : System.Web.Services.WebService { [WebMethod(true)] public string AddItemToBasket(string json) { //do stuff return myString.toJSON(); } }
问题是什么?是要发布的JSON数据的格式吗?可能是我没有在我的WebService上设置正确的属性. Dave Ward’s post中提到的问题呢
我已经尝试了我能想到的一切.有没有人有任何想法?
解决方法
我认为webservice需要设置参数json.尝试这个AJAX调用:
var data = {'name':'niall'}; $.ajax({ type: "POST",data: "json=" + JSON.stringify(data),contentType: "application/json; charset=utf-8",success: OnItemAddedSuccess });
其中JSON.stringify()是像“官方”实现中所发现的方法:http://json.org/js.html