Issue
I would like to send some data on the page to servlet
so I have written following jquery to do this
I use all data to build a json string, and directly send it to servlet
but I don't know how to get the whole data from the ajax in servlet
$("#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');}
}
);
}
);
if see the the Form Data segment of request headers from chrome
you will see the whole json string is the key.
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
Solution
Look here,
data:'{"name":"abc","address":"cde"}',
Your data
attribtue is wrong. It should not be a string, but a real JSON object. Remove those singlequotes.
data:{"name":"abc","address":"cde"},
This way it's available in the servlet the usual way
String name = request.getParameter("name"); // abc
String address = request.getParameter("address"); // cde
If it still doesn't work, head to How should I use servlets and Ajax? for complete kickoff examples, just in order to exclude that your actual problem is caused elsewhere.
See also:
Answered By - BalusC
Answer Checked By - David Goodson (JavaFixing Volunteer)