一、JSON.stringify()序列化和JSON.parse()反序列化
1 2 3 4 5
| var K = JSON.stringify(data); alert(K); var data1 = '{"name":"chunlynn" ,"age": 27, "sex": "man" ,"qq":"277539687"}'; var Kx = JSON.parse(K); layer.alert(Kx[0]['id'] + Kx[0]['username']);
|
二、ajax的注意事项
简单来说就是,在用ajax提交数据后,获取返回的结果,一定要保证后台返回时,尽量全部代码在异常处理代码中,设置出现异常返回提醒或者其他东西,不然一旦你一点代码出问题,哪怕接收的参数处理出现问题,ajax都会因为得不到后台处理该异常,一直返回error
前台:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| $.ajax({ type: "post", url: "/Home/Add/", data: { "json": JSON.stringify(data.field) }, dataType: 'text', async: false, success: function (result) { console.log(result); if ("" != result) { if (index == null) { alert('失败,失败原因:' + result); } else { parent.layer.msg('失败,失败原因:' + result, { time: 1000,shade: 0.3 }) } } else { if (index == null) { alert('添加成功' + result) } else { parent.layer.msg('添加成功' + result, { time: 1000, shade: 0.3 }) } }; }, error: function (error) { if (index == null) { alert('请稍后再试') } else { parent.layer.msg('请稍后再试', { time: 1000, shade: 0.3 }) } return false; } });
|
后台:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public string Add() { string bug = null; try { string json = Request.Form["json"]; Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(json);
string name = jobject["username"].ToString(); string sex = jobject["sex"].ToString(); string Province = jobject["Province"].ToString(); string City = jobject["City"].ToString(); string Counties = jobject["Counties"].ToString(); string Sign = jobject["Sign"].ToString(); int Experience = Convert.ToInt32(jobject["Experience"]); int Score = Convert.ToInt32(jobject["Score"]); ; int Classify = Convert.ToInt32(jobject["Classify"]); if (SQL.Add(name, sex, Province, City, Counties, Sign, Experience, Score, Classify, out bug)) { return bug; } else { return bug; } } catch (Exception) {
return "检查表单格式"; } }
|