我们平时使用ajax向后台传递数据时,通常会传递json格式的数据,当然这里还有其它格式,比如xml、html、script、text、jsonp格式。
json类型的数据包含json对象和json类型的字符串
JSON.stringify(),将JSON对象转换为JSON类型的字符串
JSON.parse(),将JSON类型的字符串转换为JSON对象
使用详情见下面4个示例。
1、直接传递json对象,示例如下:
< span style = "font-size:14px;" > < script > var jsondata ={"Participant":[{"Name_1":"1","Position_1":"1","Tel_1":"1","Mobile_1":"1","Ohter_1":"1"},{"Name_2":"1","Position_2":"1","Tel_2":"2","Mobile_2":"2","Ohter_2":"2"}]} $.ajax({ type: "POST", contentType: "application/json;charset = utf -8", url: "ApplyEdit.aspx/SaveParticipant", data: jsondata, dataType: "json", complete: function () { }, success: function (result) { }, error: function (result, status) { } }); </ script > </ span >
2、使用JSON.stringify(),将JSON对象转换为JSON类型的字符串示例如下:
< span style = "font-size:14px;" > < script > var jsondata ={"Participant":[{"Name_1":"1","Position_1":"1","Tel_1":"1","Mobile_1":"1","Ohter_1":"1"},{"Name_2":"1","Position_2":"1","Tel_2":"2","Mobile_2":"2","Ohter_2":"2"}]} $.ajax({ type: "POST", contentType: "application/json;charset = utf -8", url: "ApplyEdit.aspx/SaveParticipant", data: JSON.stringify(jsondata), dataType: "json", complete: function () { }, success: function (result) { }, error: function (result, status) { } }); </ script > </ span >
3、直接传递JSON类型的字符串,如下:
< span style = "font-size:14px;" > < script > var jsondata ="{\" name \":\""+name+"\",\"password\":\""+password+"\"}"; $.ajax({ type: "POST", contentType: "application/json;charset = utf -8", url: "ApplyEdit.aspx/SaveParticipant", data: jsondata, dataType: "json", complete: function () { }, success: function (result) { }, error: function (result, status) { } }); </ script > </ span >
4、使用JSON.parse(),将JSON类型的字符串转换为JSON对象,示例如下:
< span style = "font-size:14px;" > < script > var jsondata ="{\" name \":\""+name+"\",\"password\":\""+password+"\"}"; $.ajax({ type: "POST", contentType: "application/json;charset = utf -8", url: "ApplyEdit.aspx/SaveParticipant", data: JSON.parse(jsondata), dataType: "json", complete: function () { }, success: function (result) { }, error: function (result, status) { } }); </ script > </ span >