小编典典

如何通过servlet中的ajax获取数据?

ajax

我想将页面上的一些数据发送到servlet

所以我写了下面的jQuery来做到这一点

我使用所有数据构建一个json字符串,并将其直接发送到servlet

但是我不知道如何从servlet中的ajax获取全部数据

$("#save").click
(
    function()
    {
        $.ajax
        (
            {
                url:'/WebApplication1/Controller',
                data:'{"name":"abc","address":"cde"}',
                type:'post',
                cache:false,
                success:function(data){alert(data);},
                error:function(){alert('error');}
            }
        );
    }
);

如果查看来自chrome的请求标头的Form Data段

您会看到整个json字符串是关键。

Request URL:http://192.168.0.13/WebApplication1/Controller
Request Method:POST
Status Code:404 Not Found
Request Headersview source
Accept:*/*
Accept-Charset:Big5,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:112
Content-Type:application/x-www-form-urlencoded
Host:192.168.0.13
Origin:http://192.168.0.13
Referer:http://192.168.0.13/system_admin/building.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.910.0 Safari/535.7
X-Requested-With:XMLHttpRequest
Form Dataview URL encoded
{"name":"abc","address":"cde"}:
Response Headersview source
Accept-Ranges:bytes
Connection:Keep-Alive
Content-Language:en
Content-Type:text/html; charset=iso-8859-1
Date:Wed, 15 Feb 2012 12:37:24 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1
Transfer-Encoding:chunked
Vary:accept-language,accept-charset

阅读 499

收藏
2020-07-26

共1个答案

小编典典

看这里,

data:'{"name":"abc","address":"cde"}',

您的data归属是错误的。它不应该是字符串,而是真实的JSON对象。删除那些单引号。

data:{"name":"abc","address":"cde"},

这样,它就可以在Servlet中以常规方式使用

String name = request.getParameter("name"); // abc
String address = request.getParameter("address"); // cde

也可以看看:

2020-07-26