使用php请进入 http://blog.csdn.net/hzz780/article/details/42124607
本文最后的解决方案是使用$.post 并且在java中setPost里面setContentType(text/javascript);
应该的真实原因和$.ajax的解决方案请见我的另一博文http://blog.csdn.net/hzz780/article/details/31393513《$.ajax接受json, 返回error》
今天开发基于java的web项目的时候,在修改了java文件后,想获取json数据,发现无论如何也无法执行jquery $.ajax里的succes或是$.post或者是其他的回调函数。
jquery的情况
$.ajax({
url: "http://localhost:8080/club/privilegeGroup?act=listGroup&type=json",
data: "username=hzz",
type: 'post',
dataType: 'json',
success: function(data) {
console.log('success');
},
error: function(xhr,textStatus, errorThrown) {
console.log(errorThrown);
console.log('error');
}
});
这样执行的都是error, 但是用chrome审查元素的时候,会发现返回200OK,并且能获取数据。 从headers中看不出什么异常,设断点也没发现什么(如果谁发现了请告诉我一下。)
当时感到莫名其妙,虽然有意识想到是因为 servlet文件改了,但是还是从js这里看看吧。
纯js的情况
想起了5个状态,随又回到了纯js时光
/* test */
function createRequest () {
// body...
try {
request = new XMLHttpRequest();
}catch(tryMS){
try{
request = new AcitveXObject("Msxm12.XMLHTTP");
}catch(otherMS){
try{
request = new AcitveXObject("Microsoft.XMLHTTP");
}
catch(failed){
request=null;
}
}
}
return request;
}
function registerUser(){
var registerRequest = createRequest();
if(registerRequest==null){
}
else{
var url = "www.twt.edu.cn";//自己设置啦
var requestData = "";
registerRequest.onreadystatechange = doShow;
registerRequest.open("GET",url,true);
// registerRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
registerRequest.send(null);
}
}
function doShow(){
if (request.readyState == 4) {
if (request.status == 200) {
console.log('4');
}
}else if(request.readyState == 3){
console.log("state 3");
}else if(request.readyState == 2){
console.log("state 2");
}else if(request.readyState == 1){
console.log("state 1");
}
}
readyState 123都有,就是没有4. 遂笃定,肯定java里面改了什么东西。
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/javascript");//现在返回的是我们想要的json数据了
doGet(request,response);
}
最后发现是response.setContentType(MIME); 导致的, 它的作用是使浏览器区分不同种类的数据, 所以涉及数据交互时,大家一定要注意了。
原来传数据的时候设置成了 text/html,(或者是其他), 将其改成text/javascript即可,即能正确返回json数据了,或是解决回调函数不能执行的问题。
最后使用的代码段是
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
response.setContentType("text/html");
process(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/javascript");
doGet(request,response);
}
$.post(url, data, function(){});