Jquery的Ajax post方法返回null值。
Jquery的Ajax post方法返回null值。
我正在学习Jquery Ajax方法。我尝试使用$.post方法提交一个JSON字符串,它能够工作,但在$.Ajax方法中却不能工作,会出现500错误。请提供一些建议。
---- $.post--- 方法 // 能够工作
$.post("About.aspx?type=Test", { 'Data': '[{"Key":"454","Value":["1","3"]},{"Key":"496","Value":["1","2","3"]}]' }, function (result) { alert(result.d); }); ----c#----- public void add() { string value = Request.Form["Data"]; }
------$.Ajax post--------- 方法 // 不能工作,但是
如果我将数据传递为"{'data':'1'}",它能够工作
$.ajax({ type: "POST", url: "Contact.aspx/add", dataType: "json", data: "{'Data': '[{'Key':'454','Value':['1','3']},{'Key':'496','Value':['1','2','3']}]'}", contentType: "application/json; charset=utf-8", success: function (response) { }, error: function (msg) { alert(msg.status); } }); -----c#---- [WebMethod] public static void add( string Data) { }
问题的原因是在发送POST请求时,使用的JSON数据格式不正确。解决方法是将数据转换为字符串并使用正确的contentType。
原始的data值是一个无效的JSON字符串,应该是一个对象。同时,contentType设置不正确。可以不设置contentType,使用默认设置即可。
以下是修改后的代码:
$.ajax({ type: "POST", url: "Contact.aspx/add", dataType: "json", data: {roleList: JSON.stringify([{"Key":"454","Value":["1","3"]},{"Key":"496","Value":["1","2","3"]}])}, success: function (response) { console.log(response); }, error: function (msg) { console.log("error: ", msg.status); } });
如果不指定contentType,就无法正确访问web方法。在方法中,接受的参数是一个字符串。因此,使用JSON.stringify方法将JavaScript对象转换为字符串,并传递给服务器。如果只传递一个数据,例如"{'data' :'1'}",是可以工作的。但是对于复杂的数据结构,需要使用JSON.stringify进行转换。
希望以上修改可以帮助解决问题。