0

ajaxupload.js这里使用,我看到文件上传工作正常。但我得到<pre style="word-wrap: break-word; white-space: pre-wrap;">{"id":"006","path":"006.png"}</pre>了回应。

我认为响应应该是公正{"id":"006","path":"006.png"}的,但由于某些原因它被包裹起来<pre>,因此Uncaught SyntaxError: Unexpected token <.

我正在使用spring mvc 3,tomcat。我正在使用java.io.Writer将响应写为writer.write(json.toString());

有人可以帮我理解这个错误以及如何解决它吗?

谢谢。

更新

代码

<form id="app-form" class="cols" action="#" method="POST">
    <fieldset class="w50">                              
        <!--  set of form fields -->
    </fieldset>   
    <fieldset class="w50">                              
        <button id="uploadButton" class="csbutton-grey" >Upload</button>
        <ul id="locationImages"></ul>
    </fieldset>
<div style="float: left;">
    <button type="submit" class="cool-button">Submit</button>
</div>
</form>


$(document).ready(function(){
    var button = $('#uploadButton'), interval;

    new AjaxUpload(button, {
        action: 'uploadImage', 
        name: 'qqfile',
        responseType: "json",
        onSubmit : function(file, ext){
            this.disable();
            console.log("file - " + file);
            console.log("ext - " + ext);
            if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
                alert('Error: invalid file extension');
                return false; 
            }
            else {
                $.ajax({
                    type:"GET",
                    url:"file",
                    data:'file='+file,
                    success:function(data, textStatus, jqXHR){
                        console.log(jqXHR.status);
                        console.log(data);
                    },
                    error:function(jqXHR, textStatus, errorThrown) {
                        console.log(jqXHR.status);
                    },
                });                 
            }
        },
        onComplete: function(file, response){
            this.enable();
            console.log("file - " + file);
            console.log("response.id - " + response.id + ", response.path - " + response.path);
            $('<li></li>').appendTo('#locationImages').text(file);                      
        }
    }); 
});
4

2 回答 2

1

如果要将 JSON 发送到客户端,请使用Jackson。Spring MVC 对它有原生支持。像这样创建一个 bean 类:

public class Result{
private String id;
private String path;
public Result(String id, String path){
this.id=id;this.path=path;}
public Result(){}
// add getters and setters
}

现在像这样创建你的控制器方法

@ResponseBody // this is important
@RequestMapping("/path/to/mapping")
public Result someMethodName(SomeParameter param1, SomeParameter param2){
    // do something here
    return new Result(id, path);
}

只要您的类路径中有 Jackson 并通过 配置了 Spring 应用程序<mvc:annotation-config />,这将自动将您的响应对象序列化为正确的 JSON(包括正确的 mime 类型)

于 2012-06-05T06:23:56.890 回答
1

您是否像在 AjaxUpload 中一样设置了responseType属性?json

于 2012-06-05T06:55:53.220 回答