一个JavaScript对象传递到使用jsp页面的jQuery [英] pass a javascript object to a jsp page using jquery

查看:207
本文介绍了一个JavaScript对象传递到使用jsp页面的jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在JavaScript

VAR数据=新的对象();

和一些属性此对象是:

  data.name =迈克;
data.id = 1;
 

使用jQuery的对象传递给一个JSP页面

  VAR请求= $阿贾克斯
({
 网址:test.jsp的,
 类型:后,
 数据:'OBJ ='+的数据,
成功:函数(MSG){
     $('#响应)HTML(味精);},
  错误:函数(XHR,ajaxOptions,thrownError){
 警报(xhr.status);
 警报(thrownError);
}
});
 

在JSP我说

对象objParam =的request.getParameter(目标文件); 通过out.println(objParam.name);

这似乎并没有工作。请大家帮忙。

解决方案
  1. 因为你张贴到JSP,请确保您处理的doPost(请求,响应)方法内。
  2. 一般情况下,通过了所有的数据应该是JSON格式。你的情况,就应该读

     数据:{OBJ:数据}
     

  3. 要分析在服务器端,使用 org.json 库:

      JSONObject的OBJ =(的JSONObject)JSONValue.parse(的request.getParameter(目标文件));
        迭代器<>键= obj.keys();
        //遍历JSON对象的属性
        而(keys.hasNext()){
            字符串键=(字符串)keys.next();
            如果(obj.get(密钥)的instanceof的JSONObject){
                //一个的JSONObject中的JSONObject内
            } 其他 {
                //处理
            }
        }
     

    请参阅文档: 的JSONObject

i have in javascript

var data = new Object();

and some attributes for this object are:

data.name = "mike";
data.id = 1;

i use jquery to pass the object to a jsp page

var request = $.ajax
({
 url: "test.jsp",
 type: "post",
 data:  'obj='+ data,
success:    function(msg) {
     $('#response').html(msg);},
  error:function (xhr, ajaxOptions, thrownError){
 alert(xhr.status);
 alert(thrownError);
}  
});

in the jsp i say

Object objParam = request.getParameter("obj"); out.println(objParam.name);

this doesn't seem to work. please help.

解决方案

  1. Because you are posting to the JSP, make sure that you handle inside a doPost(request, response) method.
  2. Generally, all data passed should be in JSON format. In your case, it should read

    data: {'obj' : data}
    

  3. To parse on the server side, use the org.json library:

        JSONObject obj = (JSONObject) JSONValue.parse(request.getParameter("obj"));
        Iterator<?> keys = obj.keys();            
        //iterate over the properties of the JSON object
        while( keys.hasNext() ){
            String key = (String)keys.next();
            if( obj.get(key) instanceof JSONObject ){
                //a JSONObject inside the JSONObject
            } else {
                //process
            }
        }
    

    See the docs: JSONObject

这篇关于一个JavaScript对象传递到使用jsp页面的jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆