Ani*_*man 1 asp.net jquery json webmethod
我使用AJAX从我的js文件中调用aspx页面中的web方法.我已将方法设置为[WebMethod],页面继承自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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我在Firefox浏览器中按F12并检查网络调用中的请求/响应时,我根本看不到JSON选项卡.相反,我看到HTML标签.
我是否需要专门设置任何响应标头?我到底错过了什么?
编辑:找到一个解决方案.最终,有效的是带有回调函数的$ .getJSON()调用作为成功方法,下面是网页中的代码
result = "...";
Response.Clear();
Response.ContentType = "application/json";
Response.Write(result);
Response.Flush();
Response.End();
Run Code Online (Sandbox Code Playgroud)
谢谢大家的宝贵建议.
试试这个
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string CustomOrderService(string id)
{
string result;
// code logic which sets the result value
result="some value";
return result;
}
Run Code Online (Sandbox Code Playgroud)
CustomOrderService用以下方法装饰你的方法:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Run Code Online (Sandbox Code Playgroud)
另外,将您的退货数据更改为:
return new JavaScriptSerializer().Serialize(result);
Run Code Online (Sandbox Code Playgroud)