我已经创建了一个 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; } }
任何答复将不胜感激。提前致谢!
请您参考如下方法:
当将数据传递给$.ajax 方法时,data 参数通常是一个带有键/值对的javascript 对象,这些键/值对被放入一个foo=bar&person=ted 中的查询字符串。将一个 JSON 字符串放在那里,然后尝试在您的服务器中解析该 JSON 是向您的服务器发送几个值的困难方法,而且在服务器上解析它也需要更多的工作。
使用 $.ajax 方法的内置数据功能会将数据放入查询字符串格式,您的服务器也可以自动解析它 - 所有这些都无需在客户端或服务器上编写任何新代码.
来自jQuery docs :
data
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
