在jquery ajax中处理json响应 [英] handle json response in jquery ajax
问题描述
我想从数据库中检索数据,以单行字符串形式,并用'|'分隔我正在使用json
/ajax
/WebMethod
I want to retrieve data from database as a single row of string separated with '|' for which i am using 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}
的输出.如何将其从响应中删除?还是我在代码中做错了事
I am getting output with {"d":null}
in it. How to remove it from response ? or am i doing something wrong in code
输出:
JAMES|BOND{"d":null}
推荐答案
您将得到{"d":null}
,因为您的WebMethod
没有返回值,您只是在写入Response对象.
You are getting {"d":null}
because your WebMethod
has no return value, you are just writing to the Response object.
您应该从方法中返回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
进行访问.
And then the returned object will be {"d":"JAMES|BOND"}
, which can be accessed via response.d
in your javascript.
$.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
,以便对响应进行解析.
Please note that in the Javascript I have changed the dataType
of the Ajax response to be JSON
so that the response is parsed.
这篇关于在jquery ajax中处理json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!