2013-12-09 71 views
3

我想从数据库中检索数据作为以'|'分隔的单个字符串行,为此我使用json/ajax/WebMethod在jquery中处理json响应ajax

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

由于您的WebMethod没有返回值,您正在写入Response对象,因此您正在获得'{“d”:null}'。你应该从你的方法中返回一个字符串。然后返回的对象将是'{“d”:“JAMES | BOND”}',它可以通过JavaScript中的'response.d'来访问。 – Nunners

回答

6

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

你应该从你的方法返回一个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"},它可以通过response.d在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响应的dataTypeJSON,这样的响应解析。