简体   繁体   English

带有Spring MVC的Jquery Ajax

[英]Jquery Ajax with Spring MVC

I am making an ajax query from spring mvc JSP page.The request is made and I am able to see the json response on the browser. 我正在spring mvc JSP页面中进行ajax查询。请求已发出,我能够在浏览器中看到json响应。

$.get("${pageContext.request.contextPath}/xxx.htm", {x: y}, function(result){

        $.each(result.objects, function( index, object) {
             $(":checkbox[value="+object.id+"]").attr("checked","true");
             $( "#z" ).append(object.name+" ");
        });
    });

But, I am not getting the data in the above code. 但是,我没有在上面的代码中获取数据。 Even though the console display the json data, it also shows the error as below. 即使控制台显示json数据,它也会显示以下错误。

jquery.js:12 Uncaught TypeError: Cannot read property 'length' of undefined

at Function.each (jquery.js:12)

at Object.success

But when I copied the json data from browser and used it as a source, I am able to do the $.each(). 但是,当我从浏览器复制json数据并将其用作源时,我可以执行$ .each()。 But duting $.get(), it displays the above error. 但是在$ .get()期间,它将显示以上错误。

Can anybody help me on this? 有人可以帮我吗?

Unless your server response is setting the content to application/json jQuery will not convert it to an object in your success callback. 除非您的服务器响应将内容设置为application/json否则jQuery不会将其转换为成功回调中的对象。 So you have to set the content type specifically in the get request 因此,您必须在get请求中专门设置内容类型

$.get("${pageContext.request.contextPath}/xxx.htm", {x: y}, function(result){

        $.each(result.objects, function( index, object) {
             $(":checkbox[value="+object.id+"]").attr("checked","true");
             $( "#z" ).append(object.name+" ");
        });

}, 'json');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM