0%

JSON序列化和JSON反序列化和ajax一直返回error的解决方案

一、JSON.stringify()序列化和JSON.parse()反序列化

1
2
3
4
5
var K = JSON.stringify(data);//JSON.stringify() 将JavaScript 对象转换为 JSON 字符
alert(K);
var data1 = '{"name":"chunlynn" ,"age": 27, "sex": "man" ,"qq":"277539687"}';
var Kx = JSON.parse(K);//JSON.parse()将JSON字符串转为一个对象
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/",//url
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 })
}

// window.location.replace("AddPage");
//同步更新表格和缓存对应的值
};
},
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
/// <summary>
/// 添加
/// </summary>
/// <returns></returns>
public string Add()
{
string bug = null;
try //一定要加这个
{
string json = Request.Form["json"];
Newtonsoft.Json.Linq.JObject jobject =//这里解析出问题也会报错,可以建个新页面测试功能,查找bug
(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 "检查表单格式";
}

}