weixin_33730836 2016-07-06 21:33 采纳率: 0%
浏览 63

JSP-访问Jquery Ajax数据

I'm sending following Ajax request to mypage.jsp

   jQuery.ajax({
        type: "POST",
        url: "../mypage.jsp",
        data: {
            param1: 'aaa',
            param2: 'bbb'
        },
        contentType: "text/html; charset=utf-8",
        dataType: "text",
        success: function (data) {
            alert("Data Loaded: " + data);    
        }
    });

In my mypage.jsp page, I'm trying to access param1 as below.

String result = request.getParameter("param1");

but the result becomes null.

However, when I change my ajax request as below, I get 'aaa' as the result (which is the desired output).

   jQuery.ajax({
        type: "POST",
        url: "../mypage.jsp?param1=aaa&param2=bbb",
        data: {},
        contentType: "text/html; charset=utf-8",
        dataType: "text",
        success: function (data) {
            alert("Data Loaded: " + data);    
        }
    });

Am I using the correct method to access the data being sent by the Ajax request?

I referred some docs on Implicit Request (HTTPServletRequest) object, but could not think of any other suitable method to access data other than 'request.getParameter()'

How do I access param1 without sending it in the Ajax request URL?

Note: I also encountered a very similar SO question 'How to receive data sent by Ajax in a .jsp file' but it's not using a 'data' field as I do, hence thought to ask this question.

  • 写回答

1条回答 默认 最新

  • weixin_33726318 2016-07-07 06:55
    关注

    Following worked for me, although I'm not sure whether this and the request in the question are equivalent. However, this way, I was able to read the parameters successfully:

    new Ajax.Request('../mypage.jsp', {
        method: 'POST',
        asynchronous: false,
        parameters: {
            param1: 'aaa',
            param2: 'bbb'
        },
        onSuccess: function (data) {
            alert("Data Loaded: " + data.responseText.trim());
        }
    })
    

    Note that I had to modify the onSuccess function (data.responseText.trim()), when reading data, because here data is an object.

    评论

报告相同问题?