当前位置: 移动技术网 > IT编程>脚本编程>Ajax > 使用jquery 的ajax调用总是错误亲测的解决方法

使用jquery 的ajax调用总是错误亲测的解决方法

2017年12月12日  | 移动技术网IT编程  | 我要评论
使用jquery 的ajax功能调用一个页面,却发现总是出现错误。
js代码如下
复制代码 代码如下:

$.ajax({
type: 'post',
url: 'testdata.aspx',
data: {
language_type: 'cn'},
datatype: 'json',
success: function (data) {
alert('ok');
},
error: function (data) {
alert('err');
});
}

testdata.aspx代码如下,省略了后边一些代码
复制代码 代码如下:

<%@ page language="c#" autoeventwireup="true" codefile="testdata.aspx.cs" inherits="demand_testdata" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">

testdata.aspx.cs代码如下
复制代码 代码如下:

public partial class demand_testdata : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
list<testc> t=new list<testc> ();
for (int i = 0; i < 10; i++)
{
testc c = new testc();
c.rd_id = i;
t.add(c);
}
string test = jsonconvert.serializeobject(t);
response.contenttype = "application/json";
response.write(test);
response.clear();
}
}
public class testc
{
public int rd_id
}

可就是这么短短几行代码,jquery总是报错,如果把 datatype: 'json', 修改为其他类型就不会错了,很奇怪,可我的系统里,需要的是'json对象
最后经过反复测试才发现修改了如下地方的代码后终于正常了
1去掉testdata.aspx.cs页面中的response.clear();具体什么原因不清楚
2修改类testc为如下形式,也就是给字段添加了读取设置属性
复制代码 代码如下:

public class testc
{
private int rd_id;
public int rd_id
{
get { return rd_id; }
set { rd_id = value; }
}
}

3删除testdata.aspx页面中的所有代码,只保留第一行,修改后的代码如下
复制代码 代码如下:

<%@ page language="c#" autoeventwireup="true" codefile="testdata.aspx.cs" inherits="demand_testdata" %>

经过这么多测试终于正常了
我发现使用jquery的ajax的经常回跳入错误的处理流程,尤其是 datatype: 'json',看来jquery有很严格的验证机制,看来这个一定要注意,否则就会错误

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网