您的位置:首页 > Web前端 > JQuery

.Net+C#+Jquery实现Ajax的json应用。解决parsererror错误

2011-05-15 14:58 627 查看
1、打开vs2008新建一个WebApplication1并创建一个Handler1.ashx文件。

using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
namespace WebApplication1
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("[{/"name/":/"zhe1/",/"age/":/"80/"},{/"name/":/"zhe2/",/"age/":/"60/"}]");
}

public bool IsReusable
{
get
{
return false;
}
}
}
}


2、打开Default.aspx文件并写入以下内容。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<mce:script src="jquery.pack.js" mce_src="jquery.pack.js" type="text/javascript"></mce:script>
<mce:script language="javascript" type="text/javascript"><!--
$(function(){
$.getJSON("Handler1.ashx",
function(json){
$(json).each(function(i){
alert(json[i].name);
})
}
)
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
})

// --></mce:script>
</head>
<body>
<form id="form1" runat="server">
</form>
</body>
</html>


以上就完成了一个Json应用。

有个需要注意的地方:从jQuery 1.4开始对服务端返回的JSON 数据要求比较严格,必须严格按照JSON的标准来了。否则会出现parsererror错误。

字段字必需要使用用双引号扩起来。下面是正确的写法:

{"myvalue":1}

{"myvalue":"red"}

{"myvalue":["black",250]}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: