문제

I want to post a json string as plain string to a action ,then convert the string to List using gson, but the string is still treated as json object by jquery/webwork, I'm using jquery 1.43+webwork+gson, no jquery json plugin or something.

here is action:

public class ImageAction extends BaseAction {

    private String pks;

    public void setPks(String pks) {
        this.pks = pks;
        Gson gson=new Gson();
        List<Map> list=gson.fromJson(pks,new TypeToken<List<Map<String,String>>>(){}.getType());
        System.out.println(list.size());
    }

    ......
}

jquery code:

j$.ajax({
            url:approveUrl,
            data: {pks:'[{"userName":"theoffspring"}]'},
//            dataType:'json',
            type:'post',
//            traditional: true,
            success:function (response) {
                hideProgressBar(parent.document)
                if (response.result==false){
                    alert(response.msg);
                    return;
                }

//                document.location.reload();
            }

        })

I want pks posted as a common string instead of json object. But setPks method turns out not to be invoked when I invoke the jquery code. So strange.

도움이 되었습니까?

해결책

you have'nt serialized the data you are sending through ajax.serialize it at client using JSON.stringify() and send it will be converted to a single string.

modify your code to:

$.ajax({
            url:approveUrl,
            data:JSON.stringify(yourdata),
//            dataType:'json',
            type:'post',
//            traditional: true,
            success:function (response) {
                hideProgressBar(parent.document)
                if (response.result==false){
                    alert(response.msg);
                    return;
                }

//                document.location.reload();
            }

        })

this might work.

다른 팁

Have a look at this: http://jsfiddle.net/flocsy/vuGL9/

You'll see that your pks is actually sent as a string as you want it, when it's not sent as a string (pks2) it'll look different.

PS: look at the network tab in firebug or inspect element, depending on your browser:

pks: '[{"userName":"theoffspring"}]'

pks2[0][userName2]:'hehe'

So probably your server side does some magick...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top