【发布时间】:2012-08-28 21:41:57
【问题描述】:
我创建了一个 HTML 文件,它将尝试将 json 值传递给我的 asp 页面,但我的 asp 出现错误。我的 HTML 工作正常并传递值 {'a':'a','b':'b'},但 asp 页面无法使用该值。
-
这是我的 HTML 代码并显示 JSON 值 {'a':'a','b':'b'}:
<html> <head> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#btnAdd').click(function() { var json_obj = "{'" + $('#t1').val() + "' : '" + $('#p1').val() + "','" + $('#t2').val() + "' : '" + $('#p2').val() + "'}"; $.ajax({ type: 'POST', url: 'http://localhost/Base_Data/InsertItem.aspx', contentType: 'application/json; charset=utf-8', data: json_obj, dataType: 'json', success: function(msg) { alert('Success!'); }, error: function(msg) { alert('Error!'); } }); }); }); </script> </head> <body> <div> Type: 1: <input type="text" id="t1" /> Property 1: <input type="text" id="p1" /> Type 2: <input type="text" id="t2" /> Property 2: <input type="text" id="p2" /> <input type="button" id="btnAdd" value="Add object!" /> </div> </body> </html> -
这是我背后的 ASP 页面代码:
public class Test { public Test(string json) { var serializer = new JavaScriptSerializer(); var result = serializer.DeserializeObject(json); var first = int.Parse(result["t1"]); var second = int.Parse(result["t2"]); } public string first { get; set; } public string second { get; set; } }
任何回复都将受到高度赞赏。提前致谢!
【问题讨论】:
-
"但是 asp 页面无法使用该值" - 你能解释一下为什么吗?
-
你有什么理由使用't1'和't2'作为键。您的示例中的键由该字段中的用户输入确定。您的键 $('#t1').val() 将返回 t1 字段中的内容。如果您想使用 t1 和 t2 作为键,则将 json 设置为 {t1:value,t2:value}。也像其中一个答案中提到的那样,避免对 JSON 进行粗暴处理。使用类似 x={key1:value1,key2:value2} 的东西,很多时候你甚至不需要序列化它。如果必须使用 JSON.stringiy(x).
标签: c# javascript asp.net ajax json