加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

$.ajax json数据传递方法

发布时间:2020-12-15 21:54:29 所属栏目:百科 来源:网络整理
导读:前台代码: !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 title无标题页/title style type="text/css" .show{ display:bloc

前台代码:

<!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> 
<title>无标题页</title> 
<style type="text/css"> 
.show{ display:block;} 
.hide{ display:none;} 
</style> 
<script type="text/javascript" src="jquery/jquery-1.2.6.js"></script> 
<script type="text/javascript"> 

//这个方法把ajax方法封装一下,方便调用。 
function myajax(){ 
//var obj=jsonData(); 
$.ajax({ 
type:'post',url:'ajax.aspx',data:jsonData(),//可以直接加一个函数名。 
dataType:'json',beforeSend:beforecall,success:callback 
}); 
} 
//封装json数据,为了代码清晰 
function jsonData(){ 
var jsonStr="({"; 
jsonStr+=""name":"; 
jsonStr+=""tree""; 
jsonStr+=","; 
jsonStr+=""id":"; 
jsonStr+=""123""; 
jsonStr+="})"; 
return eval(jsonStr);//关键在于转换。 
} 
//调用前方法,不成功 
function beforecall(){ 
$('#wait').addClass("show").append('调出中...'); 
//alert('');//测试是否调用 
} 
//回调函数 
function callback(data){ 
$('#response').append(data.name+data.id); 
$('#wait').css("display","none"); 
} 
//onload()事件 
$(function(){ 
$('#confirm').click(myajax); 
}) 
</script> 
</head> 
<body> 
<div id="confirm">点击</div> 
<div id="response">接收后台数据</div> 
<div id="wait" class="hide">hello</div> 
</body> 
</html> 

后台代码:

protected void Page_Load(object sender,EventArgs e) 
{ 
Hashtable ht = new Hashtable(); 
string name = Request.Params["name"].ToString(); 
string birth = Request.Params["birthday"].ToString(); 
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(birth)) 
{ 
//Response.ContentType = "Application/json"; 
//Response.Write(CreareJson("this is ok!",1,name,birth)); 
ht.Add("info","成功了"); 
ht.Add("sta","状态"); 
ht.Add("name",name); 
ht.Add("birth",birth); 
Response.Write(CreateJsonParams(ht)); 
} 
Response.End(); 
} 
private string CreateJsonParams(Hashtable items) 
{ 
string returnStr = ""; 
foreach(DictionaryEntry item in items) 
{ 
returnStr += """ + item.Key.ToString() + "":"" + item.Value.ToString() + "","; 
} 
return "{" + returnStr.Substring(0,returnStr.Length-1) + "}"; 
} 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读