AJAX到web方法不返回JSON
我使用AJAX从我的js文件中调用aspx页面中的web方法。 我已将方法设置为[WebMethod],页面inheritance自System.Web.Ui.Page类。 它仍然没有将JSON格式返回给我的调用ajax函数。
这是js文件中的AJAX调用:
$.ajax({ type: "POST", url: "/WebServiceUtility.aspx/CustomOrderService", data: "{'id': '2'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (message) { ShowPopup(message); } }); function ShowPopup(result) { if (result.d != "") { request=result.d; } }
这是web方法:
using System; using System.IO; using System.Net; using System.Text; using System.Web.Services; namespace SalesDesk.Global { public partial class WebServiceUtility : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public string CustomOrderService(string id) { string result; // code logic which sets the result value result="some value"; return result; } } }
当我在Firefox浏览器中按F12并检查网络调用中的请求/响应时,我根本看不到JSON选项卡。 相反,我看到HTML标签。
我是否需要专门设置任何响应标头? 我到底错过了什么?
编辑:找到一个解决方案。 最终,有效的是带有回调函数的$ .getJSON()调用作为成功方法,下面是网页中的代码
result = "..."; Response.Clear(); Response.ContentType = "application/json"; Response.Write(result); Response.Flush(); Response.End();
谢谢大家的宝贵建议。
试试这个
[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string CustomOrderService(string id) { string result; // code logic which sets the result value result="some value"; return result; }
使用以下内容装饰您的CustomOrderService
方法:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
另外,将您的退货数据更改为:
return new JavaScriptSerializer().Serialize(result);
使用静态字符串 。
[WebMethod] public static string CustomOrderService(string id) { string result; // code logic which sets the result value result="some value"; return result; }
- 模态错误 – 未捕获TypeError:undefined不是函数模态
- 你如何使用jQuery获取asp:RadioButton的选中值?
- 将数据从ajax传递到mvc控制器 – null参数错误
- 如何通过ASP.Net context.Request检索JSON
- ValidateUserName未定义
- 如何从ASP Button调用JQuery?
- ASP.NET – 使用jQuery基于JSON的Web服务的正确方法是什么?
- 为什么Asp.Net MVC 5将@ Scripts.Render(“〜/ bundles / jquery”)放在_Layout.cshtml的底部?
- 编辑内部html页面,打开jQuery对话框