在html文件中ajax请求返回json响应无法触发success和error回调函数

我在html和jsp页面中写了同一段ajax请求代码,但是返回json响应结果时,
jsp能够执行success和error回调函数, 而html无法触发success和error回调函数。


  1. 在html和jsp的同一段如下ajax代码,响应成功弹框输出'OK',响应失败则弹框输出'error' <script type="text/javascript"> $(document).ready(function(){ $.ajax( { url:"filelist", type:"POST", success: function(){ alert("ok"); }, error: function(){ alert("error"); }, dataType: 'json' } ); }) </script> 2. json响应结果:

jsp成功执行success回调函数:
jsp响应结果

html则不触发success和error回调函数,直接输出了json数据:
html响应结果

在IE的下面html直接显示下载json文件:
图片说明

在web.xml中定义如下:

<!-- 以.html为后缀名访问,默认返回数据类型是 text/html, 所以要修改返回的数据类型 -->
    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> 
        <property name="mediaTypes">  
            <map>  
                <entry key="html" value="application/json;charset=UTF-8"/> 
            </map>  
        </property> 
    </bean>
    <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"

请问为什么在html中响应不会执行success或error函数??

html 中需要引入js,同时检查路径是否正确。

换google浏览器试试,你可能需要配置一下,防止后台返回json数据IE出现下载

试试把返回类型去掉,就是这个:dataType: 'json',去掉试试,或者改成其他的类型试试。

<script type="text/javascript"> 
$(document).ready(function(){ 
$.ajax( { 
url:"filelist", 
type:"POST", 
success: function(){ alert("ok"); },
error: function(){ alert("error"); }, 


dataType: 'json' } ); }) 


</script>

你写了dataType: 'json' 要返回标准json才会执行success,可能你那个json格式有点问题,必须要这种格式的
"{\"data\":\"success\"}"

找到html不响应json数据的原因了, 访问html的url被前端控制器DisptacherServlet拦截了,
然映射到了一个跟html同名的reqeustmapping方法上去了,html文件根本没执行。。。

谢谢各位的回答了。