1

我正在使用 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;
             }
         }

这是网络方法:

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();

感谢大家提出宝贵的建议。

4

4 回答 4

6

尝试这个

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string CustomOrderService(string id)
        {
            string result;
            // code logic which sets the result value
            result="some value";

            return result;
        }
于 2013-07-02T10:44:18.770 回答
5

用以下方式装饰您的CustomOrderService方法:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

此外,将您的退货数据更改为:

return new JavaScriptSerializer().Serialize(result);
于 2013-07-02T10:45:02.920 回答
0

我看到的唯一缺少的是使方法静态。

阅读这篇文章

http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

于 2014-01-28T15:06:53.163 回答
0

使用静态字符串

    [WebMethod]
    public static string CustomOrderService(string id)
    {
        string result;
        // code logic which sets the result value
        result="some value";

        return result;
    }
于 2016-04-06T06:52:19.013 回答