【问题标题】:handle json response in jquery ajax在 jquery ajax 中处理 json 响应
【发布时间】:2013-12-09 12:39:34
【问题描述】:

我想从数据库中检索数据作为用“|”分隔的单行字符串我正在使用json/ajax/WebMethod

JS

var request = {
    RefNo: $('#txtRefNo').val()
};
var strRequest = JSON.stringify(request);
$('#divDialog').html('<div>Retrieving Information...</div>').dialog({ title: 'Please Wait...', modal: true, resizable: false, draggable: false });
$.ajax({
    url: 'ajaxExecute.aspx/GETCUST',
    data: strRequest,
    dataType: "text",
    contentType: "application/json",
    cache: false,
    context: document.body,
    type: 'POST',
    error: function (xhr) {
        alert(xhr.responseText);
    },
    success: function (response) {                                        
            alert(response);
    }
});

C#

[WebMethod]
public static void GETCUST(string RefNo)
{
    try
    {
        DataTable dtOutput = new DataTable();
        dtOutput = Generix.getData("dbo.customers", "[first_name],[middle_name]", "reference_no='" + RefNo + "'", "", "", 1);
        if (dtOutput.Rows.Count > 0)
        {
            HttpContext.Current.Response.Write(dtOutput.Rows[0][0].ToString() + "|" + dtOutput.Rows[0][1].ToString());
        }
    }
    catch (Exception xObj)
    {
        HttpContext.Current.Response.Write("ERROR: " + xObj.Message);
    }
}

我得到了带有{"d":null} 的输出。如何从响应中删除它?还是我在代码中做错了什么

输出:

JAMES|BOND{"d":null}

【问题讨论】:

  • 您收到 {"d":null} 因为您的 WebMethod 没有返回值,您只是在写入 Response 对象。您应该从您的方法中返回一个字符串。然后返回的对象将是{"d":"JAMES|BOND"},可以在你的javascript中通过response.d访问。

标签: c# ajax json jquery


【解决方案1】:

你得到{"d":null} 因为你的WebMethod 没有返回值,你只是在写响应对象。

你应该从你的方法中返回一个string

[WebMethod]
public static string GETCUST(string RefNo) {
    try {
        DataTable dtOutput = new DataTable();
        dtOutput = Generix.getData("dbo.customers", "[first_name],[middle_name]", "reference_no='" + RefNo + "'", "", "", 1);
        if (dtOutput.Rows.Count > 0) {
            return dtOutput.Rows[0][0].ToString() + "|" + dtOutput.Rows[0][1].ToString();
        }
    } catch (Exception xObj) {
        return "ERROR: " + xObj.Message;
    }
}

然后返回的对象将是{"d":"JAMES|BOND"},可以在你的javascript中通过response.d访问。

$.ajax({
    url: 'ajaxExecute.aspx/GETCUST',
    data: strRequest,
    dataType: 'JSON', // Changed dataType to be JSON so the response is automatically parsed.
    contentType: "application/json",
    cache: false,
    context: document.body,
    type: 'POST',
    error: function (xhr) {
        alert(xhr.responseText);
    },
    success: function (response) {
        alert(response.d); // Should correctly alert JAMES|BOND
    }
});

请注意,在 Javascript 中,我已将 Ajax 响应的 dataType 更改为 JSON,以便解析响应。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 2012-05-15
    • 2019-04-29
    • 2014-09-28
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    相关资源
    最近更新 更多