2013-12-09 70 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,這樣的響應解析。