AJAX POST无法将数据发送到Servelet的 [英] ajax POST cannot send data to servelet

查看:145
本文介绍了AJAX POST无法将数据发送到Servelet的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个简单的Tomcat Web应用程序。客户端只发送用户名数据JSON服务器端和服务器端返回,如果这个用户名已经被注册了。 这是我的code。

AJAX部分:

  VAR UDATA =新的Array();
 udata.push({名的uname});
 $阿贾克斯({
    网址:'?/ TestProj /控制器动作= checkuname',
    键入:POST,
    数据类型:JSON,
    数据:UDATA,
    //的contentType:应用/ JSON,字符集= UTF-8,
    成功:功能(数据){
        的checkStatus = data.status;
    },
    错误:函数(X,Y,Z){的console.log(JSON.stringify(X)); }
});
 

servlet的一部分: 我使用一个控制器进行调度,以检查名的servlet。

 字符串username =的request.getParameter(姓名);

    如果(checkuser(用户名)){
        状态=假;
    }其他{
        状态=真;
    }
    response.setContentType(应用/ JSON);
    PrintWriter的O = response.getWriter();
    o.println({\状态\:\+状态+\});
    //o.println({\状态\:\+用户名+\});
 

我试着打印出的身份和用户名的内容,但它们都为null。这是否意味着我没有成功通过ajax发送的数据的servlet。我可能会搞乱JSON数据部分。 任何帮助将AP preciated。

更新时间: 我改变了ajax一部分,这和它的作品。有人可以让我知道如何做到这一点的JSON方式?

AJAX部分:

  VAR UDATA =新的Array();
 udata.push({名的uname});
 $阿贾克斯({
    网址:'?/ TestProj /控制器动作= checkuname和放大器;的uname ='+的uname,
    键入:POST,
    数据类型:JSON,
    数据:UDATA,
    //的contentType:应用/ JSON,字符集= UTF-8,
    成功:功能(数据){
        的checkStatus = data.status;
    },
    错误:函数(X,Y,Z){的console.log(JSON.stringify(X)); }
});
 

解决方案

这并没有真正意义的使用JSON对象这么简单的事情,发布用户名到一个servlet。只需使用一个简单的请求参数,并保存自己很多的麻烦。但是,如果你必须使用JSON做到这一点,有几个问题,你需要解决的问题。

  1. 除非你正在处理多个用户在同一时间,一个JavaScript数组不是数据类型的一个不错的选择。一个简单的对象,效果会更好。

      VAR UDATA = {名使用uname};
     

  2. 您交的数据应该是一个字符串,而不是一个JavaScript对象(数组或其他方式)。使用 JSON.stringify()在您的错误的功能。

      $。阿贾克斯({
        网址:'/ TestProj /控制器,
        键入:POST,
        数据类型:JSON,
        数据:'行动= checkuname和放大器;的JSONObject ='+ JSON.stringify(UDATA),
        成功:功能(数据){
            的checkStatus = data.status;
        },
        错误:函数(X,Y,Z){的console.log(JSON.stringify(X)); }
    });
     

    不过, UDATA 就是这样一个简单的JavaScript对象,你还不如自己字符串化它,因为原生JSON对象是不是要在旧的浏览器。

      VAR UDATA ='{名字:'+的uname +};
    
    $阿贾克斯({
        网址:'/ TestProj /控制器,
        键入:POST,
        数据类型:JSON,
        数据:'行动= checkuname和放大器;的JSONObject ='+的uname,
        成功:功能(数据){
            的checkStatus = data.status;
        },
        错误:函数(X,Y,Z){的console.log(JSON.stringify(X)); }
    });
     

    此外,尽管它可能归结为个人的preference,在动作参数是最好在后机身,而在查询字符串。这是一个帖子,毕竟。

  3. 的request.getParameter()是不会帮你检查JSON字符串。它只能得到请求参数的值。因此,

      JSON字符串=的request.getParameter(的JSONObject)
    //这个变量将有这样一个值{名称:somedude'}
     

    您需要解析服务器上的这个JSON字符串。你可以尝试这样做自己与字符串的方法,通过像 GSON 是一个更好的选择。你可以得到这样的用户名值:

     字符串username =(字符串)(新GSON()fromJson(JSON,Map.class)获得(名字));
     

I am working on a simple tomcat web application. The client side just send the username data in json to server side and server side return if this username is already registered. Here is my code.

ajax part:

 var udata = new Array();
 udata.push({ name: uname});
 $.ajax({
    url: '/TestProj/Controller?action=checkuname',
    type: 'POST',
    dataType: 'json',
    data: udata,
    //contentType:'application/json, charset=utf-8',
    success: function(data){
        checkstatus = data.status;
    },
    error: function(x,y,z){ console.log(JSON.stringify(x)); }
});

servlet part: I am using a controller to dispatch the request to checkname servlet.

    String username = request.getParameter("name"); 

    if (checkuser(username)){
        status = "false";
    }else{
        status = "true";
    }
    response.setContentType("application/json");
    PrintWriter o = response.getWriter();
    o.println("{\"status\":\""+status+"\"}");
    //o.println("{\"status\":\""+username+"\"}");

I try print out the content of "status" and "username", but they are both null. Does it mean that I did not successfully send out the data via ajax to servlet. I may mess up the json data part. Any help will be appreciated.

Updated: I change the ajax part to this and it works. Can someone let me know how to do it in the json way?

ajax part:

 var udata = new Array();
 udata.push({ name: uname});
 $.ajax({
    url: '/TestProj/Controller?action=checkuname&uname='+uname,
    type: 'POST',
    dataType: 'json',
    data: udata,
    //contentType:'application/json, charset=utf-8',
    success: function(data){
        checkstatus = data.status;
    },
    error: function(x,y,z){ console.log(JSON.stringify(x)); }
});

解决方案

It doesn't really make sense to use a JSON object for such a simple thing as posting a username to a servlet. Just use a simple request parameter and save yourself a lot of trouble. But if you must do it with JSON, there are a few problems you'll need to resolve.

  1. Unless you're handling multiple users at the same time, a javascript array is not a good choice of data type. A simple object would be better.

    var udata = {name: uname};
    

  2. Your post data should be a string, not a javascript object (array or otherwise). Use JSON.stringify() as in your error function.

    $.ajax({
        url: '/TestProj/Controller',
        type: 'POST',
        dataType: 'json',
        data: 'action=checkuname&jsonObject=' + JSON.stringify(udata),
        success: function(data){
            checkstatus = data.status;
        },
        error: function(x,y,z){ console.log(JSON.stringify(x)); }
    });
    

    However, udata is such a simple javascript object that you might as well stringify it yourself, as the native JSON object is not going to be available in older browsers.

    var udata = '{name:"'+uname+'"}';
    
    $.ajax({
        url: '/TestProj/Controller',
        type: 'POST',
        dataType: 'json',
        data: 'action=checkuname&jsonObject=' + uname,
        success: function(data){
            checkstatus = data.status;
        },
        error: function(x,y,z){ console.log(JSON.stringify(x)); }
    });
    

    Also, although it may boil down to personal preference, the action parameter is better off in the post body rather in the query string. This is a post, after all.

  3. request.getParameter() is not going to help you inspect a JSON string. It can only get the value of request parameters. So

    String json = request.getParameter("jsonObject")
    // this variable will have a value like "{name: 'somedude'}"
    

    You'll need to parse this JSON string on the server. You could try to do this yourself with String methods, by a library like Gson is a much better option. You could obtain the username value like this:

    String username = (String)(new Gson().fromJson(json, Map.class).get("name"));
    

这篇关于AJAX POST无法将数据发送到Servelet的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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