getjsontest.jsp部分
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>getjson</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
//$.getJSON(url,data,success(data,status,xhr));
$.getJSON("getJsonData.do",function(data,status,xhr){
alert(data);
//$("#jsondata").html(data.id+":"+data.text+":"+data.desc);
});
});
</script>
</head>
<body>
<div id="jsondata"></div>
</body>
</html>
getJsonData.java部分
package com.iflytek.ajaxtest;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class getJsonData extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html,charset=utf-8");
PrintWriter pw = resp.getWriter();
pw.print("JSONObject{\"id\":1,\"text\":\"Java\",\"desc\":\"Write once,run anywhere\"}");
}
}
$.getJSON(url,[data],[callback]); 不应该是三个参数吗?你写三个参数试试
代码代码如下:
$.getJSON("data.php",$("#firstName.val()"),function(jsonData){
$("#getJSONResponse").html(jsonData.id);}//无需设置,直接获取的数据类型为json,
所以调用时需要使用jsonData.id方式
);
这个getJsonData.do的映射是怎么设置的,怎么没有找到呀,你直接在浏览器中访问,看能不能获取相对应的数据
回调函数执行成功,应该是你Json字符串的问题
pw.print("JSONObject{\"id\":1,\"text\":\"Java\",\"desc\":\"Write once,run anywhere\"}");
你没有创建json对象,这是一个字符串