2017-08-05 40 views
1

有一種函數可以使用Jquery Ajax從數據庫中獲取名稱。該功能具有輸入參數,我用下面的代碼獲得它:Jquery - 嘗試將數據發送到Ajax,但數據爲空

var value = $(this).parent().find(":checkbox").val(); 
var typeSelect = GetLayerGeometries(value); 

然後將值發送到AJAX功能:

的Ajax功能

function GetLayerGeometries(LayerName) { 
    var data; 
    $.ajax({ 
     url: 'GetLayerGeometries.aspx/GetLayerGeometry', 
     data: '{"LayerName":"' + LayerName + '"}', 
     async: false, 
     success: function (resp) { 
      data = resp; 
      callback.call(data); 
     }, 
     error: function() { } 
    }); 
    return data; 
} 

C#功能:

protected void Page_Load(object sender, EventArgs e) 
{ 
    string test = Request.Form["LayerName"]; 
    GetLayerGeometry(Request.Form["LayerName"]); 
} 

public void GetLayerGeometry(string LayerName) 
{ 
    WebReference.MyWebService map = new WebReference.MyWebService(); 
    string Name = map.GetLayerGeometries(LayerName); 

    if (Name != null) 
     Response.Write(Name);    
} 

我的問題:LayerName爲空。

我使用this link並測試所有方法,但LayerName仍爲空。

+0

是'值'null在您的JavaScript? – sheplu

+0

不,值不爲空。 'Request.Form [「LayerName」]爲空。 – Farzaneh

+0

你正在傳遞數據爲JSON,但試圖閱讀它,就好像它是形式編碼 - 我認爲這是你的問題。 – abagshaw

回答

1
function GetLayerGeometries(LayerName) { 
    var data; 
    $.ajax({ 
     url: 'GetLayerGeometries.aspx/GetLayerGeometry', 
     data: {"LayerName":LayerName}, 
     async: false, 
     success: function (resp) { 
      data = resp.d; 
      callback.call(data); 
     }, 
     error: function() { } 
    }); 
    return data; 
} 

[WebMethod] 
public static string GetLayerGeometry(string LayerName) 
{ 
    return LayerName 
} 

你需要使用web方法就像上面的方法。

+0

LayerName仍爲空。 – Farzaneh

+0

顯示我屏幕截圖您的js html和cs頁面。 –

0

問題是,你正在試圖解析請求體,就好像它是編碼的形式一樣,事實並非如此。你已經使用JSON傳遞了數據,所以你需要適當地解析它。

使用在C#以下使用Json.NET從JSON讀取請求變量:

protected void Page_Load(object sender, EventArgs e) 
{ 
    string requestBody = StreamReader(Request.InputStream).ReadToEnd(); 
    dynamic parsedBody = JsonConvert.DeserializeObject(requestBody); 
    string test = parsedBody.LayerName; 
} 
+0

LayerName仍爲空。 – Farzaneh

+0

你的意思'測試'結束了'null'? 'requestBody'最終是什麼? – abagshaw

0

您需要字符串化的值,然後把它,它會工作

function GetLayerGeometries(LayerName) { 
    var data; 
    $.ajax({ 
     url: 'GetLayerGeometries.aspx/GetLayerGeometry', 
     data: { LayerName: JSON.stringify(LayerName) }, // make this change 
     async: false, 
     success: function (resp) { 
      data = resp; 
      callback.call(data); 
     }, 
     error: function() { } 
    }); 
    return data; 
}