JS一个var如何接受后台传回json数据

easyUI有个demo上面是这样的

 <script>
var products = [
{productid:'FI-SW-01',name:'Koi'},
{productid:'K9-DL-01',name:'Dalmation'},
{productid:'RP-SN-01',name:'Rattlesnake'}]
<script>
 <body>
<th field="productid" width="100" formatter="productFormatter" editor="{type:'combobox',options:{valueField:'productid',textField:'name',data:products,required:true}}">Product</th>
</body>

就是一个下拉选有3个选项,Koi、Dalmation和Rattlesnake,现在说我的下拉选的选项需要从后台获取数据,那么我想要这个var products = 后台获得的json数据,怎么做?就是一个json数据赋值给JS变量问题,我试过在函数里面定义一个var接受json数据但是不行。如下:

 $.ajax({
url:'${pageContext.request.contextPath}/AjaxRegistration_list'
})
.done(function(response){
console.log("success"+JSON.stringify(response));
var products = JSON.stringify(response);
//这里能打印出json数据,但是上面的var products好像并不能被th中的editor使用data:products这样接受
alert(products);
})
.fail(function(){
console.log("error")
});

7个回答

不清楚你返回json的response内容是怎样,假如是这样的:

 {
   "data" :
      [
         {
            "productid" : "FI-SW-01",
            "name" : "Koi",
         },
         {
            "productid" : "K9-DL-01",
            "name" : "Dalmation",
         }
      ],
   "success" : true
}

栗子:

 <script>
var products = [];
for(var i=0;i<response.data.length;i++){
    var obj=response.data[i];
    products.push({
        productid:obj.productid,//'FI-SW-01',
        name:obj.name//'Koi'
    })
}
console.log(products);
</script>
EncodingGentleman
EncodingGentleman 是格式问题,我犯2了,解决了,谢谢!
一年多之前 回复
xing2208
xing2208 回复EncodingGentleman: 取不出是作用域问题,你要先定义变量才能被外部使用
一年多之前 回复
EncodingGentleman
EncodingGentleman 返回的json格式是这样的[ { "productid" : "FI-SW-01", "name" : "Koi", }, { "productid" : "K9-DL-01", "name" : "Dalmation", } ],但是现在好像不是格式问题,我直接var products = 【{....}】这种直接手动输入不用后台获取的方式,把var定义在$(function(){//这里面}),取不出来,把var products定义在<script>//定义在这里</script>就可以
一年多之前 回复

combobox需要的数据格式是[
{productid:'FI-SW-01',name:'Koi'},
{productid:'K9-DL-01',name:'Dalmation'},
{productid:'RP-SN-01',name:'Rattlesnake'}]数组格式的;
我觉得你应该是数据格式不对吧。

EncodingGentleman
EncodingGentleman 谢谢!
一年多之前 回复

你应该用JSON.parse()而不是用JSON.stringify()

zhaokun900124
zhaokun900124 回复EncodingGentleman: 嗯,你需要在外边先定义products才行,你在内部定义在外边是取不到的
一年多之前 回复
EncodingGentleman
EncodingGentleman 解决了,谢谢,上边老哥的代码有用,分给他了,没办法给多个,抱歉
一年多之前 回复
zhaokun900124
zhaokun900124 回复EncodingGentleman: 你在外边定义var products = {}试试
一年多之前 回复
EncodingGentleman
EncodingGentleman 格式问题我应该能解决,我主要是解决不了<script>var products = [{}]</script>和<script>$(function(){var products=[{}]})这
一年多之前 回复
EncodingGentleman
EncodingGentleman 用JSON.parse()就报错Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) at Object.eval (eval at <anonymous> (jquery-1.7.2.min.js:2), <anonymous>:48:20) at o (jquery-1.7.2.min.js:2) at Object.fireWith [as resolveWith] (jquery-1.7.2.min.js:2) at w (jquery-1.7.2.min.js:4) at XMLHttpRequest.d (jquery-1.7.2.min.js:4)
一年多之前 回复

var url = "admin/FrmQueryAllGroup.do";
$.getJSON(url,function(json) {
$('#cc').combobox({
data: json.jsonResult.rows,
valueField: 'ID',
textField: 'TEXT'
});
});

$.ajax({
type: "POST",
url: 'admin/FrmQueryAllGroup.do',
dataType: "json",
success: function(json) {
$('#cc').combobox({
data: json.jsonResult.rows,
valueField: 'ID',
textField: 'TEXT'
});
}
});

EncodingGentleman
EncodingGentleman 谢谢老哥
一年多之前 回复


Product

不用看都知道跟你的插件方式冲突,你想想直接js接受可以,这样不可以,要么是你的插件不支持这样获取,要么是你这个地方获取的方式有问题
baidu_33403616
再写三行 回复EncodingGentleman: 解决了就好
一年多之前 回复
EncodingGentleman
EncodingGentleman 是获取的json字符串后取法错误了,谢了老哥
一年多之前 回复

你得把你console输出的response贴出来,才能看到你response响应的值,根据这个值去取值

EncodingGentleman
EncodingGentleman 我问题解决了,你这这个办法好,以后这么搞。
一年多之前 回复

你前面已经定了products,你再回调函数里面又重新定义了products,这个回调函数里的变量成了局部变量,不会赋值上层的全局变量products。

EncodingGentleman
EncodingGentleman 懂了,谢谢你的回复
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
js如何获取后台json数据
一定要通过response吗rn如果写ajax请求应该怎么写
EasyUI 如何接受后台发来的Json数据
加载页面的时候,不会显示数据rn[code=java]rnrn rn rn rn rn 图书名称rn rn rn rn rn 编号rn 数量rn 单价 rn 总价 rn rn rn rnrn rn[/code]rnrn但是后台能正确执行rn
EasyUI 如何接受后台发来的Json数据,并用datagrid接受显示
如标题。rn详细描述:rn1, 加载页面的时候,datagrid不会显示数据;rn2, 在页面中调用如下代码:[code=javascript]rn rolenode = $('#tg').treegrid('getSelected');//获得选中的rolern $.post('RoleAuthorityAction_getAllRoleAuthority.action' , roleNo:rolenode.roleNo , function(result)rn console.info("thsi roelNo =" + rolenode.roleNo);rn //1 刷新数据表格 rn //$('#tg_roleauthority').datagrid('load');rn //$('#tg_roleauthority').datagrid('reload');rn $('#tg_roleauthority').datagrid('loadData');rn //2 清空idField rn //$('#tg_roleauthority').datagrid('unselectAll');rn //3 给提示信息 rn $.messager.show(rn title:'提示信息!' , rn msg:'操作成功!'rn );rn );rnrn[/code]rn后台正确执行,用firebug查看消息如下:[img=https://img-bbs.csdn.net/upload/201506/20/1434809437_62503.png][/img]rnrn3,使用[code=javascript]$('#tg_roleauthority').datagrid('reload');[/code]也加载不来数据,rnrn调得筋疲力竭了。。。[img=https://forum.csdn.net/PointForum/ui/scripts/csdn/Plugin/003/monkey/50.gif][/img]
如何将json数据传回前台
当Ajax访问后台 ,后台的json信息如何传回到前台
json数据传回前台报错。
[code=Java]2011-05-22 11:19:58,640 ERROR [org.apache.struts.actions.DispatchAction] - rnjava.lang.reflect.InvocationTargetExceptionrn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)rn at java.lang.reflect.Method.invoke(Unknown Source)rn at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270)rn at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187)rn at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:110)rn at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)rn at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)rn at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)rn at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at cn.com.sedee.centermanager.appclass.CharacterEncodingFitler.doFilter(CharacterEncodingFitler.java:29)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)rn at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:75)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96)rn at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:75)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)rn at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)rn at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)rn at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)rn at java.lang.Thread.run(Unknown Source)rnCaused by: java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpherrn at cn.com.sedee.struts.action.SbdmbAction.outPrint(SbdmbAction.java:121)rn at cn.com.sedee.struts.action.SbdmbAction.getSbzt(SbdmbAction.java:103)rn ... 36 morern2011-05-22 11:19:58,640 WARN [org.apache.struts.action.RequestProcessor] - rn2011-5-22 11:19:58 org.apache.catalina.core.StandardWrapperValve invokern严重: Servlet.service() for servlet action threw exceptionrnjava.lang.NoClassDefFoundError: net/sf/ezmorph/Morpherrn at cn.com.sedee.struts.action.SbdmbAction.outPrint(SbdmbAction.java:121)rn at cn.com.sedee.struts.action.SbdmbAction.getSbzt(SbdmbAction.java:103)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)rn at java.lang.reflect.Method.invoke(Unknown Source)rn at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270)rn at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187)rn at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:110)rn at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)rn at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)rn at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)rn at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at cn.com.sedee.centermanager.appclass.CharacterEncodingFitler.doFilter(CharacterEncodingFitler.java:29)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)rn at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:75)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96)rn at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:75)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)rn at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)rn at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)rn at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)rn at java.lang.Thread.run(Unknown Source)[/code]rnrn [code=Java]rnpublic ActionForward getSbzt(ActionMapping mapping, ActionForm form,rn HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException rn Map model=new HashMap();rn String strid=(String)request.getParameter("paramid");rn List list=sbdmbService.getSbdmb(strid);rn PingSBZT pingSBZT = new PingSBZT();rn List objlist=new ArrayList();rn for (int i = 0; i < list.size(); i++) rn String sbmc = list.get(i).getSbmc().toString();rn String sbip = list.get(i).getSbip().toString();rn String zt = pingSBZT.pingSBZT(sbip);rn System.out.println("设备名称:"+sbmc+":"+zt);rn rn SbdmbDto dto=new SbdmbDto();rn dto.setId(list.get(i).getSbId());rn dto.setSbmc(sbmc);rn dto.setSbzt(list.get(i).getSbzt());rn dto.setSblx(list.get(i).getSblxb().getSblxmc());rn dto.setSbip(sbip);rn dto.setLjzt(zt);rn objlist.add(dto);rn rn rn model.put("sbdmlist", objlist);rn outPrint(request,response,model);rn return null;rn rnrn public void outPrint(HttpServletRequest request, HttpServletResponse response, Map model) rn PrintWriter writer = null;rn response.setContentType("text/text; charset=utf-8");rn try rn writer = response.getWriter();rn catch (IOException e) rn rn model.put("error", "error.action.AjaxAction.outprint_writer");rn rn if (model.isEmpty())rn writer.println("0");rn else rn prePrint(request, response, model);rn JSONObject json = new JSONObject();rn json.putAll(model);rn writer.println(json);rn writer.close();rn rn rn[/code]rnrn报错的行为:rnrn [code=Java]rn prePrint(request, response, model);rn 121 JSONObject json = new JSONObject();rn json.putAll(model);rn writer.println(json);rn writer.close();rn[/code]rnrn
服务器传回json数据的问题
最近刚接触ajax,碰到个小问题,还想请前辈指点。rnajax到服务器后,服务器传回json数据,比如(....,imgPath:"...\...")这样,rn其中有一个属性imgPath是图片的绝对路径,在前台js里 用一个 msg成功获取到。但使用了jsonObj=eval(msg);之后jsonObj.imgPath里的"\" 全部消失了...,其他的都很正常。rn请问这种情况应该怎么处理呢?谢谢了...rnrn
js如何读取asp.net后台json数据
如题后台的json数据,是转换dataset来的。如何在前台用js将json读取出来?rn并且分级(跟三级联动差不多)
关于Ajax前台Json数据的接受和后台数据解析
关于Ajax前台Json数据的接受和后台数据解析具体问题方法解析一.不添加contentType 属性二.添加contentType:&quot;application/json&quot; 属性总结 具体问题 最近在使用Ajax做前后台数据传输时发现了一个问题,就是使用jQuery使用Ajax时是否添加contentType : &quot;application/json; charset=utf-8&quot;属性碰到的坑,下面...
Jersey+Spring集成,后台接受或返回Json数据
NULL 博文链接:https://arthur8.iteye.com/blog/1954736
JS遍历后台传过来的JSON数据
这两天解决了一下ssh框架的json数据传输问题. 第一步:首先,在ssh框架中要想传输json数据,必须导入相关的依赖包,以下是我使用的版本的系列(由于jar包版本的问题,导入不同版本很容易出错误). json-lib-2.4-jdk15.jar 这个jar包依赖的的有五个包: commons-beanutils-1.8.0.jar commons-collections-
JS前台替换后台传回的换行符
使用Ajax从服务器端返回json数据时如果有回车符(\r\n),客户端解析会出错: 所以在这之前先将回车符替换掉才行 json.replace(&quot;\r\n&quot;, &quot;&amp;lt;BR&amp;gt;&quot;);//单个替换 json.replace(/\\r\n/g, &quot;&amp;lt;BR&amp;gt;&quot;));//全部替换 或者  json.replace(/\r/ig, &quot;&quot;).replace(/\n/ig,&quot;
struts2 json 前台传一个集合类型的json数据后台接受不到
首先前台调用: $("#json").bind("click",function()rn rn var jsons = userList:["age":88,"email":"feiji@qq.com","id":70,"keshi":"骨 科","passWord":"feiji","phoneNumber":"34234","sex":1,"userId":"23432432","userName":"feiji","userType":1];rn //alert(para);rn $.ajax(rn type:"POST",rn url:"jsontest",rn datatype:"json",rn data:jsons,rn success:function(msg)rn alert(msg.userList[0].userName);rn rn );rn );rnrn后台:rnrn private List userList;rnrn public List getUserList() rn return userList;rn rnrn @JSON(serialize = true, deserialize = true)rn public void setUserList(List userList) rn this.userList = userList;rn rn public String execute() rn // this.name = "feiji";rn // System.out.println("========" + name + "=======");rn // this.name = "daifei";rn System.out.println("userList size:" + userList.size()rn + "**************");rn System.out.println(userList.get(0).getUserName()rn + "$$$$$$$$$$$$$$$$$$$$$$");rn return SUCCESS;rn rnrnstruts 配置: rn rn rn rn rn rn userList\[\d\]\.userNamern rn rnrn执行后控制台输出: [DEBUG] 2012-04-10 10:45:51 :Executing action method = nullrn userList size:1**************rnnull$$$$$$$$$$$$$$$$$$$$$$rnrn [DEBUG] 2012-04-10 10:45:51 :Adding include property expression: userListrn [DEBUG] 2012-04-10 10:45:51 :Adding include property expression: userList\[\d\]rn [DEBUG] 2012-04-10 10:45:51 :Adding include property expression: userList\[\d\]\.userNamern [DEBUG] 2012-04-10 10:45:51 :Ignoring property because of include rule: namern [DEBUG] 2012-04-10 10:45:51 :Ignoring property because of include rule: userrn [DEBUG] 2012-04-10 10:45:51 :Ignoring property because of include rule: userList[0].agern [DEBUG] 2012-04-10 10:45:51 :Ignoring property because of include rule: userList[0].emailrn [DEBUG] 2012-04-10 10:45:51 :Ignoring property because of include rule: userList[0].idrn [DEBUG] 2012-04-10 10:45:51 :Ignoring property because of include rule: userList[0].keshirn [DEBUG] 2012-04-10 10:45:51 :Ignoring property because of include rule: userList[0].passWordrn [DEBUG] 2012-04-10 10:45:51 :Ignoring property because of include rule: userList[0].phoneNumberrn [DEBUG] 2012-04-10 10:45:51 :Ignoring property because of include rule: userList[0].sexrn [DEBUG] 2012-04-10 10:45:51 :Ignoring property because of include rule: userList[0].userIdrn [DEBUG] 2012-04-10 10:45:51 :Ignoring property because of include rule: userList[0].userTypern [DEBUG] 2012-04-10 10:45:51 :[JSON]"userList":["userName":null]rnrnrn也就是说数据json数据没有封装到userList 中去,我调试了好就找不到原因rnrnrn
桌面html文件ajax提交json数据到后台,后台无法接受数据
桌面html文件ajax提交json数据到后台,后台无法接受数据,但是这个html文件放在项目下却可以通过ajax提交json数据
c++ 接受函数传回的数组
c++ 接受函数传回的数组 举一个简单的例子: #include &amp;lt;iostream&amp;gt; using namespace std; int *f(int n){ int* R=new int[n]; //这里很关键,要new一个空间,不然在编译的时候虽然不会报错,但是结果会出错 for(int i=0;i&amp;lt;n;i++){ ...
如何传回一个数组?
我想由一个函数传回一个数组:rnrnrn int Num[3];rn Num[0]=...;rn Num[1]=...;rn Num[2]=...;rnrn //??return Numrnrnrn如果传回指针由于数组已经离开作用域,是要被delete的,内存被释放了又如何得到我想要的数组呢?
js如何读取json数据
读取数据的时候报错“编译错误: 缺少 ']'”,难道是格式不对?rnC# codernrn public string LoadData()rn rn string sql = "select [Lat],[Lng],[strong] from [dbo].[Test_LatLng]";rn DataTable dt = database.Query(sql);rn if (dt != null && dt.Rows.Count > 0)rn rn string str = "[";rn int i = 0;rn for (i = 0; i < dt.Rows.Count; i++)rn rn str = str + "Lat:" + dt.Rows[i]["Lat"].ToString()+",";rn str = str + "Lng:" + dt.Rows[i]["Lng"].ToString()+",";rn str = str + "strong:" + dt.Rows[i]["strong"].ToString() + "";rn rn str = str + "]";rn return str;rnrn rnrn elsern rn return "";rn rnrnrn读取rnC# codern function addmarkers() rn var vb = Map.maptest.LoadData().value;rn var jsonData = eval("(" + vb + ")");rnrn
如何接受var a = "";传过来的数据?
标题可能不对,问题是这样的rnvar a = "1";rnif (a!=2) rn Str = '一';rnrn else rn Str = '二';rnrnrndocument.write(Str);rnrn当a=1时显示一rn当a不=1时显示二rnrn我想rn当a=1时显示一rn当a=2时显示二rn当a=3时显示三rn当a不=1或2或3时就显示零rnrn这个应该怎么改??rnrn我知道在ASP里这样是可以的rna = 1rnIf a = 1 thenrn Str = "一"rnElseIf a = 2 thenrn Str = "二"rnElseIf a = 3 thenrn Str = "三"rnElsern Str = "零"rnEnd IfrnResponse.Write Strrnrn但在JavaScript中我用同样的原理行不通。。。。。。rnrnrn请那位大哥告诉我在JavaScript中如何实现这个功能?
请教如何解决 JS中接受服务器端传来的JSON数据乱码问题
JS代码:rnrnrn $.get("FlxsAction",null,function(data)rn rn rn //alert("back");rn //var lmObj = eval("("+data+")");rn var lmObj = data;rnrn if(lmObj.length!=0)rn rn for(var i = 0 ; i"+lmObj[i]+"").appendTo(flxs);rn rn rn ,"json");rnrnrn服务器端是一个Action(Struts2)rnrnrn LmListDAO lm = new LmListDAO();rn ArrayList lmlist = lm.getLmList();rn if(lmlist!=null)rn Gson g = new Gson();rn String listToJson = g.toJson(lmlist);rn System.out.println("-----Gson类型转换------");rn System.out.println(listToJson);rn out.write(listToJson);//此处控制台输出没有乱码rn rnrnrn请大家给个建议! 谢谢! rn
springMVC接受前台json数据
网上各种说json数据的各种好处,但是之前前后端自己一个人做,体会不到json的好, 突然有前端写页面,告诉我所有交互数据都是json,很爽啊有木有. 大多数情况下正好接受要么数据少的时候,把参数放到请求后,要么数据多正好有实体对应, 就那么少数情况下,参数也不多,但总拼接多链接后感觉很low,就想到,json可是使用对象接受, 但json本质就是一个map形式的数据格式,直接使用map应
webService 接受提交的JSon数据
1、controller @RequestMapping(value = "saveJson") @ResponseBody public Map saveJson(HttpServletRequest request) throws IOException { Map map = new HashMap(); String submitMethod = request.getMet
jquery如何接收后台的json数据
thinkphp部分:rn控制器:Home/index/sessrn输出:$data = json_encode($aaa);rn echo $data;rn前台已经输出"aaa":"\u4e00\u4e00\u7c7b","bbb":"\u4e8c\u4e00\u7c7b","ccc":"\u4e09\u4e00\u7c7b" ,对应的URL路径http://127.0.0.1/home/sess?aaa=4&bbb=7&ccc=9rn请问用jquery怎么获取sess的json数据?网上的get,post,getJSON,Ajax都试着套了,不知道弄,好苦闷!!!rn求大神!!![img=https://forum.csdn.net/PointForum/ui/scripts/csdn/Plugin/001/face/56.gif][/img]
从后台得json数据用js嵌套循环
使用ajax传递数据,返回json对象 var url = "${ctx}/meeting/meetingreceice/?meetingId=${meeting.id}"; $.getJSON(url, function (result) { var html = ""; $.each(result.data, function () { html += ""
js获取后台传来的json数据错误
后台数据[img=https://img-bbs.csdn.net/upload/201803/22/1521710331_994164.png][/img]rnrn前台数据[img=https://img-bbs.csdn.net/upload/201803/22/1521710354_464395.png][/img]rnrn获取的数据不完全,页面报的错误为:Uncaught SyntaxError: Invalid shorthand property initializerrnrn该怎么解决哦
js接收后台json数据的中文乱码问题
前台:javascript 后台:servlet 前台代码: 放在head里面 后台代码: response.setContentType("text/html;charset=UTF-8");
js前台无法展示后台的传递的json数据
这几天在学习json,在网上找了个例子,通过数据库查询信息,封装成json格式,展示在前台的表格上,我把例子中的代码复制下来,然后稍微改了下,结果是只能展示表格,数据却没法展示出来,不知原因出在什么地方。初学前端的东西,很多都不清楚,希望大家指教下谢谢。rn网页上的结果:rn[img=https://img-bbs.csdn.net/upload/201608/23/1471940162_654932.jpg][/img]rn代码如下:rn//数据库操作代码rnpackage dao;rnrnimport java.sql.Connection;rnimport java.sql.DriverManager;rnimport java.sql.PreparedStatement;rnimport java.sql.ResultSet;rnrnpublic class StudentDao rn private Connection con;rn public StudentDao()rn String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //加载JDBC驱动rn String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=pubs"; //连接服务器和数据库testrn String userName = "sa"; //默认用户名rn String userPwd ="940828"; //密码rn try rn Class.forName(driverName);rn con = DriverManager.getConnection(dbURL, userName, userPwd);rn System.out.println("Connection Successful!"); rn catch (Exception e) rn e.printStackTrace();rn rn rn public ResultSet query(String sql, Object... args) throws Exception rn PreparedStatement ps = con.prepareStatement(sql); rn for (int i = 0; i < args.length; i++) rn ps.setObject(i + 1, args[i]); rn rn return ps.executeQuery(); rn rn protected void finalize() throws Exception rn if (!con.isClosed() || con != null) rn con.close(); rn rn rnrnrn//Servlet代码rnpackage control;rnrnimport java.io.IOException;rnimport java.io.PrintStream;rnimport java.sql.ResultSet;rnrnimport javax.servlet.ServletException;rnimport javax.servlet.http.HttpServlet;rnimport javax.servlet.http.HttpServletRequest;rnimport javax.servlet.http.HttpServletResponse;rnrnimport dao.StudentDao;rnrnpublic class StudentServlet extends HttpServlet rnrn rn public StudentServlet() rn super();rn rnrnrn public void doGet(HttpServletRequest request, HttpServletResponse response)rn throws ServletException, IOException rn rn PrintStream out = new PrintStream(response.getOutputStream()); rn response.setContentType("text/html;charSet=utf-8"); rn out.print("请正常打开此页"); rn rn rn rn rnrn rn public void doPost(HttpServletRequest request, HttpServletResponse response)rn throws ServletException, IOException rn StringBuffer json = new StringBuffer(); rn json.append("["); rn try rn StudentDao db = new StudentDao(); rn ResultSet rs = db.query("select * from Student"); rn while (rs.next()) rn json.append(''); rn //注意每一个key-value对都要在引号之中,单引号或者双引号都可以 rn json.append("'id':").append("'").append(rs.getInt("id")).append("'").append(","); rn json.append("'name':").append("'") rn .append(rs.getString("name").trim()).append("'").append(","); rn json.append("'tender':").append("'") rn .append(rs.getString("tender").trim()).append("'"); rn json.append(","); rn rn rn catch (Exception e) rn e.printStackTrace(); rn rn //这是为了删除最后一次循环中出现的那个逗号 rn json.deleteCharAt(json.length() - 1); rn json.append("]");rn PrintStream out = new PrintStream(response.getOutputStream()); rn response.setContentType("text/html;charSet=utf-8"); rn //搞完把json打印在本Servlet上,之后前台页面读这页的内容就可以了 rn out.println(json.toString()); rn out.close(); rn rnrnrn//js代码rnrnrn rn StudentDemo.htmlrn rn rn rn rn rn rn rn rn rn rn 查询 rn rn rn rnrn//配置文件rnrnrn MyControlrn control.MyControlrn rn rn StudentServletrn control.StudentServletrn rnrn rn MyControlrn /mycontrolrn rn rn StudentServletrn /StudentServletrn
Ajax从后台查询处理json数据JS方法
//查询 function doSearch(){ var operateDateStart=$(&amp;quot;#operateDateStart&amp;quot;).val(); var operateDateEnd=$(&amp;quot;#operateDateEnd&amp;quot;).val(); var materialCod...
js 解析后台json数据的常用方式
写在前面的话:本文借鉴互联网大神的做法,整理而得,只为总结工作,学习提高。var str = ‘{&quot;name&quot;:&quot;crp&quot;,&quot;age&quot;:&quot;20&quot;,&quot;weight&quot;:&quot;50kg&quot;,&quot;data&quot;:{&quot;pinvince&quot;:&quot;湖北&quot;,“city”:“武汉”,&quot;area&quot;:&quot;洪山区&quot;}}’1.使用ev
在js中获取后台转换的json数据
后台框架是struts2 + ibatis + spring rn页面上做了个类型的级联菜单,代码是这样的:rn[code=Java]rn页面文件MobTsM-showAreaData.jsprn rn 投诉分类 rn rn rn rn rn $complainNamern rn rn rn rn rn 投诉细类 rn rn rn rn rn $complainDetailsNamern rn rn rn[/code]rn通过对大类的change事件来查询细类内容 再返回到下拉框里,rnchange事件是通过Ajax来查询的,rn[code=JScript]rnfunction getComplainDetailsInfo()rn var details = document.getElementById('complainInfo');rn var detailsName = details.options(details.selectedIndex).text; rn var para = 'complainName='+detailsName;rn var url="<%=basePath %>report/mobtsm/MobTsM!findComplainDetail.action";rn new Ajax.Updater(rn 'details',rn url,rn rn asynchronous: true,rn method:'post',rn parameters:para,rn onSuccess:getDeTails //[color=#FF0000]回调函数[/color]rn rn );rn rnrn[/code]rn[code=Java]rn后台代码:rnpublic String findComplainDetail() rn complainDetailList = getDssDaoHelper().queryForList("mobTsMT.findComplainDetailList", this.complainName); rn this.moduleJson = Utils.toJsonString(complainDetailList);rn return "showAreaData"; //查询完成返回到该页面rn rn//这里的list,moduleJson数据都有rn[/code]rn[code=JScript]rn回调函数:rnfunction getDeTails()rn //var str1 = eval(moduleJson);//这样也是获取不到数据。rn var str = Re.responseText.evalJSON();rn alert(Str); rn rn//这里想通过回调函数来获取json数据,但是在这里获取不到,后台也没有报错。rn//请问各位大侠是不是这样写有什么问题?应该怎么获取?谢谢了!!!在线等!rn[/code]rnrn
前台js如何接受后台的值
[code=csharp]rnfor (int i = 0; i < GridView1.Rows.Count; i++) rn CheckBox chk = (CheckBox)GridView1.Rows[i].FindControl("CheckBox");rn chk.Attributes.Add("onclick", "chkCount(this)");rnrn[/code]rn[code=javascript]rnfunction chkCount() rn alert"1");rn rn[/code]rn如上,前台js如何获得i的值
thinkphp的模板里面如何接受json数据
比如我在控制器中读取数据库数据,并且将其展示在模板中,但是其中有一个字段的值是1,2rn在模板中我想将其分开展示,请问怎么弄。用foreach嵌套吗
哭求:如何传回一个数组?
比如rnmain()rnrn int x = 100;rnrn a( x ); /* 请问这里该用什么来接收返回的数组? */rnrnrnint a( int x )rnrn int b[] = 1 , 2 , 3 ,n = 0;rnrn for( ; n < 3 ; n++ ) rn b[n] = b[n] + x;rn rnrn /* 这里该如何把这个b数组传回去啊?传回去函数的返回类型需要改吗?请各位大大详细告诉我 */rn
后台传回的时间带 T
后台传回的时间带 T
函数如何传回一个数组
定义一个函数,此函数能传回一个数组。怎么做?
ajax json数据提交请求和后台SpringMVC接受请求数据
//ajax 提交到后台 var param = {"unusualType":unusualType};             $.ajax({                 type: 'post',                 url: "checkAllUnusualType.htm?CSRFToken="+$("#CSRFToken").val(),          
关于微信小程序接受后台json数据汉字变成问号
最近做微信小程序开发,发现后台传来的json数据里面的中文全变成了“?”    如下图:          上网找也没找到解决方法,后来经过自己调试半天,突然就解决了,解决方案如下图所示:           把 请求,响应的编码格式和类型的语句 都放在  PrintWriter out = resp.getWriter()  语句的前面就  解  决  了!!!
接受http post过来的json数据
Post发送JSON数据格式如下:rnrn "SchoolData": rn "School": "北京八中",rn "ExaminationRoom": "01"rn ,rn "curriculum": [rn rn "CourseName": "语文",rn "Number": 1,rn "Class": "101室"rn ,rn rn "CourseName": "数学",rn "Number": 3,rn "Class": "102室"rn rn ],rn "Date": "2017-06-08"rnrnrn怎么把post过来的json数据接收解析录入到数据库里,效果如下:rna表rnSchool ExaminationRoom CourseName Class Datern北京八中 01 语文 101室 2017-06-08rn北京八中 01 数学 102室 2017-06-08rn北京八中 01 数学 102室 2017-06-08rn北京八中 01 数学 102室 2017-06-08rnrn望给代码示例
spring使用对象接受json数据
map接收json ``` //{"1":"11111","2":"22222","3":"33333"} console.log(JSON.stringify(obj)); $.ajax({url:"frAddDelVal/testReq?=", type:"post", dataType:"json", contentType:"applicati
flexigrid 接受json数据时的问题
前台页面:::rn rnrnrnrnrnservlet中返回的json:::rn PrintWriter out = response.getWriter();rn rn String json=""; rn json+="\"id\":\"tiny\","; rn json+="\"name\":\"123\","; rn json+="\"remark\":\"123\","; rn json+="\"test1\":\"123\""; rn out.write(json); rn rn rnrnrn?????问题:rn前台为什么出不来数据
如果接受从dll组件传回的值?
如果接受从dll组件传回的值?rnrn谢谢,在线等待
Struts2框架接受/返回json数据
Struts接口可以从流中接受json数据并解析,并以流的形式返回给前端。如下所示: public class testController extends ActionSupport{ private InputStream inputStream; private String getRequestPostData(HttpServletRequest request)...
相关热词 c# 去空格去转义符 c#用户登录窗体代码 c# 流 c# linux 可视化 c# mvc 返回图片 c# 像素空间 c# 日期 最后一天 c#字典序排序 c# 截屏取色 c#中的哪些属于托管机制