我正在尝试使用json对象从jsp文件传输数据。
这是我的JavaScript代码:
// action when item file is clicked
$("li span.file").click(function(){
// get the ID
alert(' Forward the url when clicked WITH ID => ' + $(this).attr('id'));
$.getJSON('BomItemToJSON', function(data) {
alert('entered getJSON()');
$.each(data, function(i, item) {
alert('entered each()');
var id = item.id;
var description = item.description;
alert('description: ' + description);
formObject = document.forms['itemForm'];
formObject.elements['itemId'].value = id;
formObject.elements['itemDescription'].value = description;
alert('done with javascirpt');
});
});
});
这是我的Servlet,应该由JavaScript调用:
public class BomItemToJSON extends HttpServlet {
private static final long serialVersionUID = 1L;
@PersistenceContext(unitName = "xxx")
public EntityManager em;
@Resource
UserTransaction utx;
Logger logger = Logger.getLogger(this.getClass().getCanonicalName());
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("bom item to json servlet has been called.");
try {
utx.begin();
} catch (NotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//int id = Integer.parseInt(request.getParameter("id"));
BomHandling bh = new BomHandling(em, utx);
BomItem item = bh.getBomItem(63788);
Gson gson = new Gson();
String json = gson.toJson(item);
System.out.println("Json: " + json);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
try {
utx.commit();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RollbackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HeuristicMixedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HeuristicRollbackException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是我的web.xml,它映射了Servlet:
<servlet>
<display-name>BomItemToJSON</display-name>
<servlet-name>BomItemToJSON</servlet-name>
<servlet-class>com.xxx.servlets.BomItemToJSON</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BomItemToJSON</servlet-name>
<url-pattern>/BomItemToJSON</url-pattern>
</servlet-mapping>
当我点击该项目时,我收到提示“点击带有ID时转发网址”。但似乎没有调用getJSON()函数。为什么呢?
答案 0 :(得分:0)
一些调试技巧可以找到丢失的内容:
另外,我个人喜欢只在jQuery中使用$ .ajax函数而不是它们的简写。