我将 jQuery AJAX POST 发布到 servlet,数据采用 JSON 字符串的形式。我不确定数据是否被发布。另外,我想通过从 json 对象中获取登录名和密码来验证它。
下面是代码片段:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
function doajax(){
var fullname=$("#fullname").val;
var mobileno=$("#mobileno").val;
$.ajax({
url: 'dvsds',
type: 'POST',
dataType: 'json',
data:{ "mobileno":mobileno, "fullname":fullname},
error:function(){
alert("error occured!!!");
},
success:function(data){
alert(data.message);
}
});
}
</script>
我的 servlet 端代码:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
try {
String message=null;
JSONObject jObj = new JSONObject(request.getParameter("jsondata"));
Iterator<String> it = jObj.keys(); //gets all the keys
String Name=null;
String mobileno=null;
while(it.hasNext())
{
String key = (String) it.next(); // get key
if(key.equals("fullname"))
Name = (String)jObj.get(key);
else if(key.equals("mobileno"))
mobileno=(String)jObj.get(key);
}
if(Name=="abc" && mobileno=="123" )
message="success";
else
message="fail";
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", message);
out.println(jsonObject);