如何使用ajax将json传入后台数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用ajax将json传入后台数据相关的知识,希望对你有一定的参考价值。

首先采用jquery内部封装好的方法是比较简单的,我们只需做的就是修改里面的一些配置:

以下代码是对$.ajax()的解析:
$.ajax(
type: "POST", //提交方式
contentType: "application/json; charset=utf-8", //内容类型
dataType: "json", //类型
url: "前台地址/后台方法", //提交的页面,方法名
data: "parameter", //参数,如果没有,可以为null
success: function (data) //如果执行成功,那么执行此方法
alert(data.d); //用data.d来获取后台传过来的json语句,或者是单纯的语句
,
error: function (err) //如果执行不成功,那么执行此方法
alert("err:" + err);

);

当然我初次学习的时候,看到这些也是有些茫然的,因为不知道到如何才能将其用到自己的程序里面,所以就写了一个小的检测网页来测试一下,如果你测试的时候没有达到你想要的结果,那么希望你回头看一下,前台是否写的有问题,或者是参考一下下文中的注意事项吧。

前台代码 :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="number3.aspx.cs" Inherits="ajax1.number3" %>
<!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>测试ajax</title>
<script src="js/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
function testAjax()
$.ajax(
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "number3.aspx/GetJson",//传入后台的地址/方法
data: "\'RID\':\'123\'",//参数,这里是一个json语句
success: function (data)
var result = data.d;
alert(result);
,
error: function (err)
alert("err:" + err);

);

</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<button >用button测试ajax</button>
<input type="button" value="testAjax" />
</div>
</form>
</body>
</html>

后台代码:
using System;
using System.Web.Services;
namespace ajax1

public partial class number3 : System.Web.UI.Page

protected void Page_Load(object sender, EventArgs e)


[WebMethod]
public static string GetJson(string RID)

return "\'ID\':\'" + RID + "\'";




后台代码中以黄色为背景的就是我们要注意的地方:

1.using System.Web.Services;对应下面的[WebMethod]这个一定要加上的。

2.后台写的方法一定是公共静态的即一定是public static开头的。

3.参数一定是前台的data所传参数的键

前台中要注意的地方:

1.大家应该会注意到,前台我用的是两个button来测试,但是第一个<button>是不行的,页面会刷新一下,其实这都是<form
id="form1"
runat="server">这行代码的问题,<button>标签会提交本页面的内容,从而导致异步刷新失败。所以建议大家不要用<button>标签。但是如果不得不用的话,解决办法还是有的,目前我知道的只有两个:

  ①:将<form id="form1"
runat="server">代码去掉,当然如果本页面有要提交的内容就会很麻烦了

  ②:将<button onclick="aaa();return
false;">用button测试ajax</button>代码改为:<button
onclick="aaa();return false;">用button测试ajax</button>

2。前台的测试结果是:

那么我们如何来只获取json后面的值,而不是整个json语句呢,我们可以将json语句对象化,然后根据键来取得对应的值:前台的testAjax()的方法改为:
function testAjax()
$.ajax(
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "number3.aspx/GetJson",
data: "\'RID\':\'123\'",
success: function (data)
var result = eval("(" + data.d + ")");//这句话是将json语句对象化
alert(result.ID);
,
error: function (err)
alert("err:" + err);

);


此时结果为:

以上就是初步学习json当时遇到的问题所留下的经验。同时我想验证一下是否能够在后台重载方法来实现根据前台的data是否有参数来判断要执行的方法,所以我将代码改动了一下:
改动后的前台代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="number3.aspx.cs" Inherits="ajax1.number3" %>
<!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>测试ajax</title>
<script src="js/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
function testAjax()
$.ajax(
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "number3.aspx/GetJson",
data: "\'RID\':\'123\'",
success: function (data)
var result = eval("(" + data.d + ")");
alert(result.ID);
,
error: function (err)
alert("err:" + err);

);

function aaa()
$.ajax(
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "number3.aspx/GetJson",
success: function (data)
alert(data.d);
,
error: function (err)
alert("err:" + err);

);

</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<button >用button测试ajax</button>
<input type="button" value="testAjax" />
<input type="button" value="aaa" />
</div>
</form>
</body>
</html>
改动后的后台代码
using System;
using System.Web.Services;
namespace ajax1

public partial class number3 : System.Web.UI.Page

protected void Page_Load(object sender, EventArgs e)


[WebMethod]
public static string GetJson()

return "hello ajax";

[WebMethod]
public static string GetJson(string RID)

return "\'ID\':\'" + RID + "\'";




所得的效果为:

第一个和第二个按钮点击后效果为:

第三个按钮点击后效果为:

所以我的初步结论为:后台的重构函数是不成功的,如果有的重构参数的话,只会执行带参数的,而不会执行那个不带参数的。现在还不是太明白为什么会这样,所以希望明白原理的分享一下自己的观点。当然这只是个人观点,如若有误,望请指正。
参考技术A

proCityArea_JsonData.js

$(function()
proCityAreaJsonData2();
);
//前台ajax的参数data提交jsonObj
function proCityAreaJsonData1()
$.ajax(
type:"post",
url:myContextPath+"/back/sqlTable/jsonData1",
    data:pCAJson: JSON.stringify(pCAJson),//或data:"pCAJson": JSON.stringify(pCAJson) 。data的key键可"",也可不""
dataType:"json",//dataType是接收服务器的时候的数据类型
success:function(data)

,
error:function()


);

//前台ajax的参数data提交jsonStr
function proCityAreaJsonData2()
var pCAJsonObj="pCAJson":pCAJson;
var jsonObjStr=JSON.stringify(pCAJsonObj);

$.ajax(
type:"post",
url:myContextPath+"/back/sqlTable/jsonData2",
contentType:"application/json;charset=utf-8,application/json",//contentType是传输过去的时候的数据类型
    data:jsonObjStr,//data的key键可"",也可不""
dataType:"json",//dataType是接收服务器的时候的数据类型
success:function(data)

,
error:function()


);

JsonDataToSQL.java

@Controller
@RequestMapping("/back/sqlTable")
public class JsonDataToSQL 
public static void main(String[] args) 


/**
 * 
* @Description: TODO(前台ajax的参数data提交jsonObj,到后台) 
* @param request
* @param response
* @param params
* @return 
* @Grammer1:request.getParameter("key");
根据map对象的key-value格式,此getParameter方法的参数为key,返回值为字符串类型value。
key的属性值value必须为字符串类型,否则null。
* @Grammer2:若前台ajax的参数data提交jsonStr。可以使用data:param:JSON.stringify(data)的方式就能将对象变成字符串,同时指定contentType:"application/json",dataType: "json",这样就可以轻易的将一个对象或者List传到后台。
若前台ajax的参数data提交jsonObj。
后台@RequestBody接收的其实是一个Json对象的字符串,而不是一个Json对象。
 */
@RequestMapping("/jsonData1")
@ResponseBody
public static String ergodicJsonDataToListMap1(HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String, Object> params)
String pCAJsonStr1=(String) params.get("pCAJson");
String pCAJsonStr2=request.getParameter("pCAJson");
return pCAJsonStr2;

/**
 * 
* @Description: TODO(前台ajax的参数data提交jsonStr,到后台) 
 */
@RequestMapping("/jsonData2")
@ResponseBody
public static String ergodicJsonDataToListMap2(HttpServletRequest request,HttpServletResponse response,@RequestBody String pCAJsonStr)
//String paramVal=request.getParameter("pCAJson");//由于前台ajax传来的jsonStr中,pCAJsonObj="pCAJson":pCAJson;pCAJson键对应的值,数据类型不是字符串。//null
pCAJsonStr=pCAJsonStr;
return pCAJsonStr;

参考技术B

首先,我们来写一下后台如何生成要传输的数据:

这样,就可以把数据无刷新的写入到数据库。

Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。

Ajax = 异步 JavaScript 和 XML(标准通用标记语言的子集)。Ajax 是一种用于创建快速动态网页的技术。Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。

Ajax中参数带有html格式的 传入后台保存

因业务需求  要讲如下编辑器中带有样式的数据传入数据库保存

第一种方法  json格式传入

 1   $(".privilegezn_page .btn_ok").click(function () {
 2         if (editor.html() == "")
 3         {
 4            alert("优惠使用指南内容不能为空")
 5         } else {
 6             var str = HTMLEncode(editor.html());
 7             console.log(str);
 8                 if (($("select")).length > 0) {
 9                     var hotelid = $("#hotel option:selected").attr("value");
10                 } else {
11                     var hotelid = $("#hotelid").val();
12                 }
13                 var cz = $("#xg").val();//操作名id
14                 var gnbh = $("#gnbh").val();
15                 var obj = new Object();
16                 obj.text = str;
17                 obj.xgid = hotelid;
1 function HTMLEncode(text){ 
2 text = text.replace(/&/g, "&") ; 
3 text = text.replace(/</g, "\'<\'") ; 
4 text = text.replace(/>/g, "\'>\'") ; 
5 return text; 
6 }

 

18                 obj.gnbh = gnbh;
19                 obj.cz = cz;
20                 console.log(JSON.stringify(obj));
21                 $.ajax({
22                     type: "POST",
23                     url: "/Business/yhsyznxg",
24                     data:{json:JSON.stringify(obj)},
25                     success: function (data) {
26                         var f = $.parseJSON(data);
27                         if (f.yz1) {
28                             alert("添加成功!");
29                             if ($("#yhsyzncx").length > 0) {
30                                 $("#yhsyzncx").trigger("click");
31                             } else {
32                                 location.replace(location.href);
33                             }
34                         }
35                         else if (f.yz1 == false) {
36                             alert("添加失败!");
37                             location.replace(location.href);
38                         }
39                         if (f.yz2) {
40                             alert("修改成功!");
41                             if ($("#yhsyzncx").length > 0) {
42                                 $("#yhsyzncx").trigger("click");
43                             } else {
44                                 location.replace(location.href);
45                             }
46                         }
47                         else if (f.yz2 == false) {
48                             alert("修改失败!");
49                             location.replace(location.href);
50                         }
51                     }
52                 });
53            }   
54     })

后台页面:

 1  //优惠使用指南
 2         [HttpPost]
 3         public ActionResult yhsyznxg(string json)
 4         {
 5             JObject l = (JObject)JsonConvert.DeserializeObject(json);
 6             //数据库为空则添加
 7             int xgid = (int)l["xgid"];
 8             int gnbh = (int)l["gnbh"];
 9             int cz = (int)l["cz"];
10             string text = (string)l["text"];
11             string str = text.Replace("\'<\'", "<");   //解码去除 html中<  >
12             string str1 = str.Replace("\'>\'", ">");
13             var cx = db.yhsyzn.FirstOrDefault(u => u.hotelid == xgid);
14             JObject array = new JObject();
15             if (cx != null) //修改
16             {
17                 if (Session["yhid"] != null)
18                 {
19                     int id = (int)Session["yhid"];
20                    
21                     bool pd = qxyz.czyz(id, gnbh, cz); //为什么还要查询一遍权限
22                     if (pd)
23                     {
24                         yhsyzn a = db.yhsyzn.FirstOrDefault(u => u.hotelid == xgid);//查询到对应id
25                         a.text = str1;
26                         db.Entry(a).State = System.Data.Entity.EntityState.Modified;  //什么更新???
27                         db.SaveChanges();
28                         array["yz2"] = true;
29                     }
30                     else
31                     {
32                         array["yz2"] = false;
33                     }
34                 }
35                 else
36                 {
37                     array["yz2"] = false;
38                 }
39             }
40             else //添加
41             {
42                 if (Session["yhid"] != null)
43                 {
44                     int id = (int)Session["yhid"];
45                     bool pd = qxyz.czyz(id, gnbh, cz); //为什么还要查询一遍权限
46                     if (pd)
47                     {
48                         yhsyzn a = new yhsyzn();
49                             a.hotelid = xgid;
50                             a.text = text;
51                             db.yhsyzn.Add(a);
52                             db.SaveChanges();
53                             array["yz1"] = true;
54                     }
55                     else
56                     {
57                         array["yz1"] = false;
58                     }
59                 }
60             }
61             return Content(array.ToString());
62         }

 

以上是关于如何使用ajax将json传入后台数据的主要内容,如果未能解决你的问题,请参考以下文章

gomain函数中如何动态获取数据

jquery用ajax方式从后台获取json数据后如何将内容填充到下拉列表

Ajax中参数带有html格式的 传入后台保存

传入一个数组和2个字符串 以及后台如何接收

ajax中回调的几个坑

AJAX如何解析后台传来的json数据?