jQuery Ajax中如何处理JSON响应

3
我希望能够使用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}

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

6

您收到 {"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,以便解析响应。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接