2017-08-05 66 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; 
}