我的$ .getJSON方法正在调用servlet,但回调函数不起作用。
这是我的js文件:
$(document).ready(function() {
$('p').addClass('highlight');
receiveData();
});
function receiveData(){
alert('receive data');
$.getJSON('ProcessForm', function(data){alert('hi')});
}
屏幕上出现“接收数据”警报,以及调用ProcessForm Servlet,但回调方法中的警报未到来。
这就是我在ProcessForm Servlet中编写的内容
package com.nagarro.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.nagarro.json.DictionaryList;
public class ProcesFormServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response)
throws ServletException, IOException {
DictionaryList dictionaryList = new DictionaryList();
System.out.println("haan ji sir");
// Write response data as JSON.
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(dictionaryList));
super.doGet(req, response);
}
protected void doPost(HttpServletRequest req, HttpServletResponse response)
throws ServletException, IOException {
DictionaryList dictionaryList = new DictionaryList();
System.out.println("haan ji sir");
// Write response data as JSON.
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(dictionaryList));
super.doPost(req, response);
}
}
任何人都知道可能是什么问题
答案 0 :(得分:0)
你有可能没有返回结构良好的JSON吗?这会导致jquery不执行回调代码。
如果您确定是(通过JSON Lint站点运行以进行仔细检查),请确保在HTTP响应的标头中指定Content-type:application / json
答案 1 :(得分:0)
将$ .getJSON更改为通用$ .ajax,然后添加错误回调。错误回调中的jqXHR对象应该告诉您请求失败的原因(很可能是XSS“No Transport”错误)
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/