ajax on aui:select liferay

眉间皱痕 提交于 2019-12-24 03:31:00

问题


I know this is impossible to pass parameter from javascript to scriptlet code in jsp page So I want to use ajax to post my selected value to server and then get it in scriptlet code by request object I use

<aui:select label="My Selection" name="ms" id="ms" onchange="<%= updateItem()%>" >
    <%
    for(String item : itemList){            
    %>
    <aui:option selected="<%= item.equals(selItem) %>" value="<%=item%>"><%=item%></aui:option>         
    <%}%>
</aui:select>

<%! 
private Object updateItem() throws Exception{
    //to do something with selected value
return null;
}%>

Please show me how to excute ajax post in this tag, or any tag can be used in my scenario


回答1:


You don't seem to realize at all how HTTP and web applications work. You have to learn about request/response cycle.

The AJAX is the right thing to you for what you want to do, but as name says AJAX is Asynchronous JavaScript - and you try to put java method call in your onchange attribute. This won't work.

To do what you ask for first, you have to find your Portlet class, and implement serveResource(ResourceRequest req, ResourceResponse resp) method, where you will be receiving the selected value ( String selectedVal = req.getParameter("selectedVal") ) and returning something depending on that value.

String result = null; 
if ("blah".equals(selectedVal))
  { result = "Something"; } 
else 
  { result = "Something Else"; } 
resourceResponse.getPortletOutputStream().write(result.getBytes("UTF-8")); 

Then you have to make your AJAX calls to that method. Should roughly look like this:

<portlet:resourceUrl var="resourceUrl">
<portlet:param name="selectedVal" value="PARAM_PLACEHOLDER_SELECTED_VAL" />
</portlet:resourceUrl>
<aui:script use="io">
function ajax<portlet:namespace />MySelect(selectedVal) {
        A.io(
            '${resourceUrl}'.replace("PARAM_PLACEHOLDER_SELECTED_VAL", selectedVal),
            {
                on: {
                    success: <portlet:namespace />processResponse(select, response);
                }
            }
        );

function <portlet:namespace />processResponse(response) {
alert("Here's what java code returned:"+response+". Do whatever you want with it - with javascript");
}
</aui:script>

...

<aui:select label="My Selection" name="ms" id="ms" onchange="ajax<portlet:namespace>MySelect(this.values[this.selectedIndex])" >
    <%
    for(String item : itemList){            
    %>
    <aui:option selected="<%= item.equals(selItem) %>" value="<%=item%>"><%=item%></aui:option>         
    <%}%>
</aui:select>

Hope this helps.




回答2:


Suppose we have a two select, one is for selecting subject and another one is populating topic automatically according subject selection: This example I've tried with Ajax and was successful!

**In JSP:**

1. declare this in your jsp

    <portlet:resourceURL var="fetchTopicsResourceURL" />
after 
        <portlet:defineObjects />
  1. First select option for subject selection

     <aui:select id="subject" name="subject" label="Subject"
        inlineField="true" onChange='<%= renderResponse.getNamespace() + "fetchTopics();"%>'>
        <aui:option selected="true" value="">
            <liferay-ui:message key="Please select one.." />
        </aui:option>
        <%
            int totalsubject = SubjectLocalServiceUtil
                            .getSubjectsCount();
                    List<Subject> subjectList = SubjectLocalServiceUtil
                            .getSubjects(0, totalsubject);
                    for (Subject subject : subjectList) {
        %>
        <aui:option value="<%=subject.getSubjectId()%>"><%=subject.getSubjectName()%></aui:option>
    
        <%
            }
        %>
    

  2. second select option for populating topics automatically according subject selection above.

  3. write a javascript function which will be executed onChange of the value of subject as shown:

    Liferay.provide(
        window,
        '<portlet:namespace />fetchTopics',
        function() {
    
            var A = AUI();
    
            var fetchTopicsURL = '<%= fetchTopicsResourceURL.toString() %>';
    
            // selecting the sourceSelect drop-down to get the current value
            var sourceElement = A.one("#<portlet:namespace />subject");
    
            // selecting the targetSelect drop-down to populate values
            var targetElement = A.one("#<portlet:namespace />topic");
    
            A.io.request (
                // the resource URL to fetch words
                fetchTopicsURL, {
                data: {
                    // request parameters to be sent to the Server
                    <portlet:namespace />subject: sourceElement.val()
                },
                dataType: 'json',
                on: {
                        failure: function() {
                            // if there was some error at the server
                            alert("Ajax failed! There was some error at the server");
                        },
                        success: function(event, id, obj) {
    
                            // JSON Data recieved from Server
    
                            var topicsArray = this.get('responseData');
    
                            // crude javascript magic to populate the drop-down
    
                            //clear the content of select
                            targetElement.html("");
    
                            for (var j=0; j < topicsArray.length; j++) {
    
                                targetElement.append("<option value='" + topicsArray[j] + "'>" + topicsArray[j] + "</option>");
                            }
                        }
                    }
                }
            ); 
        },
        ['aui-io']
    );
    

That's all your jsp coding! :)

Next part is to write a method your portlet class as shown below:

 @Override
    public void serveResource(ResourceRequest resourceRequest,
            ResourceResponse resourceResponse) throws IOException,
            PortletException {

        String subject = ParamUtil.getString(resourceRequest, "subject");

        // build the JsonArray to be sent back
        JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

        //put some topics
        if(subject.equals("Maths")){
        jsonArray.put("Math1");
        jsonArray.put("Math2");
        jsonArray.put("Math3");
        }
        if(subject.equals("Science")){
        jsonArray.put("science1");
        jsonArray.put("science2");
        jsonArray.put("science3");
        }


        // set the content Type
        resourceResponse.setContentType("text/javascript");

        // using printWrite to write to the response
        PrintWriter writer = resourceResponse.getWriter();

        writer.write(jsonArray.toString());
    }

That's all your coding.. :)



来源:https://stackoverflow.com/questions/11645517/ajax-on-auiselect-liferay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!