我正在开发一个网页(ASP.NET 4.0),我只是开始简单地尝试让这个ajax调用工作(我是一个ajax / jQuery新手)并且我在调用时遇到错误。这是js:
var TestParams = new Object;
TestParams.Items = new Object;
TestParams.Items[0] = 1;
TestParams.Items[1] = 5;
TestParams.Items[2] = 10;
var finalObj = JSON.stringify(TestParams);
var _url = 'AdvancedSearch.aspx/TestMethod';
$(document).ready(function ()
{
$.ajax({
type: "POST",
url: _url,
data: finalObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg)
{
$(".main").html(msg.d);
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(thrownError.toString());
}
});
这是我的代码隐藏文件中的方法:
[Serializable]
public class TestParams
{
public List<int> Items { get; set; }
}
public partial class Search : Page
{
[WebMethod]
public static string TestMethod(TestParams testParams)
{
// I never hit a breakpoint in here
// do some stuff
// return some stuff
return "";
}
}
这是我发回的字符串化的json:
{"Items":{"0":1,"1":5,"2":10}}
当我运行它时,我收到此错误:
Microsoft JScript运行时错误:'undefined'为null或不是对象
它打破了错误功能。
我也尝试过使用这个最终的json构建json(基于网站上的示例)的这种变体:
var TestParams = new Object;
TestParams.Positions = new Object;
TestParams.Positions[0] = 1;
TestParams.Positions[1] = 5;
TestParams.Positions[2] = 10;
var DTO = new Object;
DTO.positions = TestParams;
var finalObj = JSON.stringify(DTO)
{"positions":{"Positions":{"0":1,"1":5,"2":10}}}
相同的错误消息。
从网页上向我的web方法发送一个int列表似乎并不难。有什么想法吗?
谢谢, 杰
答案 0 :(得分:4)
我试过这个,它在.NET 3.5中运行。不同之处在于序列化后的数组就像项目:[1,2] 在.aspx
var _url = 'Default.aspx/TestMethod';
$(document).ready(
function() {
$.ajax(
{
type: "POST",
url: _url,
data: '{"i":{"Items":[1,2]} }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$(".main").html(msg.d);
},
error: function(xhr, ajaxOptions, thrownError) {
debugger;
alert(thrownError.toString());
}
}
)
}
);
在.cs
[WebMethod]
public static string TestMethod(TestParams i)
{
return "whaever";
}
我从这个
获得了字符串var serializer = new JavaScriptSerializer();
var param = new TestParams();
var list = new List<int> {1, 2};
param.Items = list;
string serializedString = serializer.Serialize(param);
希望这有帮助。
答案 1 :(得分:3)
更改'TestParams.Items = new Object();' 到
TestParams.Items = new Array();
答案 2 :(得分:1)
问题可能是您的代码隐藏类缺少 scriptservice 属性,无法通过脚本访问webmethod。请参阅此http://msdn.microsoft.com/en-us/library/system.web.script.services.scriptserviceattribute.aspx。
答案 3 :(得分:0)
我可能错了,但看起来你应该试试这个:
[Serializable]
public class TestParams
{
public List<int> Items { get; set; }
}
public partial class Search : Page
{
[WebMethod]
public static string TestMethod(List<int> finalObj)
{
TestParams testParams = new TestParams { Items = finalObj };
//Use whatever method you have to return the testParams as JSON
return testParams;
}
}
在回调中,您必须获取数据。项目:
success: function (msg)
{
$(".main").html(msg.Items);
},
希望这会有所帮助:)