java Spring MVC:在进行 AJAX 调用后在对话框中显示数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17267609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:31:26  来源:igfitidea点击:

Spring MVC: Show data in a dialog after making an AJAX call

javajqueryajaxspringjsp

提问by Amarnath

I am new to Spring and web technology.

我是 Spring 和 Web 技术的新手。

I have an table which contains a column with hyperlink. When I click on the hyperlink of a row, I need to display that rows data along with other details in a dialog. My controller method returns a ModelAndViewwhich contains the data I need to show and the display page.

我有一个表格,其中包含一个带有超链接的列。当我单击一行的超链接时,我需要在对话框中显示该行数据以及其他详细信息。我的控制器方法返回一个ModelAndView包含我需要显示的数据和显示页面。

Problems:

问题:

  1. How to show the dialog? and

  2. How to pass the data to the dialog?

  1. 如何显示对话框?和

  2. 如何将数据传递给对话框?

Table.jsp

表.jsp

<script type="text/javascript">
   function showDialog(ref, date) {

        $ajax({
            type: "POST",
            url: "/example/show.htm",
            data: {
                ref: ref,
                date: date
            }
            success: function(data) {

            },
            error: function(data) {

            }
        });
}
</script>

Mapping

映射

@RequestMapping(value = "show.htm", method=RequestMethod.POST)
    public ModelAndView show(@RequestParam("ref") String ref, @RequestParam("date") String date, 
            HttpServletRequest request, HttpServletResponse response) {

        ModelAndView modelAndView = new ModelAndView();

        try {
            SampleDTO SampleDTO = new SampleDTO();
            sampleDTO.setDate(sdf.parse(date));
            sampleDTO.setRef(ref);

            SampleDTO billDto =  // server call                    modelAndView.addObject("showBill", sampleDto);

            modelAndView.setViewName("Dialog");
        } 
        return modelAndView;
    }

回答by Oscar Jara

Your code is wrong, you are messing things, if you want to use jQueryand ajaxcalls then don't use ModelAndViewin your Springcontroller. Instead of that, use the following and returnyour beanor dtoas a jsonusing Hymansonlibrary from Java:

你的代码是错误的,你把事情搞砸了,如果你想使用jQueryajax调用,那么不要ModelAndView在你的Spring控制器中使用。取而代之的是,使用以下内容和return您的beandto作为来自的json使用HymansonJava

Include this jarin your libproject folder:

将其包含jar在您的lib项目文件夹中:

http://www.java2s.com/Code/JarDownload/Hymanson/Hymanson-all-1.9.9.jar.zip

http://www.java2s.com/Code/JarDownload/Hymanson/Hymanson-all-1.9.9.jar.zip

Java code:

爪哇代码:

@RequestMapping(value = "businessBill.htm", method = RequestMethod.POST)
@ResponseBody
public String handleBusinessBillDetails(@RequestParam("reference") String billReference, @RequestParam("invoiceDate") String billDate, 
            HttpServletRequest request, HttpServletResponse response) {

    String json = null;        

    try {

        //1. Create 'Hymanson' object mapper
        ObjectMapper objectMapper = new ObjectMapper();  

        BusinessBillDTO businessBillDTO = new BusinessBillDTO();
        businessBillDTO.setBillDate(sdf.parse(billDate));
        businessBillDTO.setBillReference(billReference);

        BusinessBillDTO billDto = accountStatementBO.getBusinessBillDetails(businessBillDTO);

        //2. Convert your 'bean' or 'dto' as 'json' string
        json = objectMapper.writeValueAsString(billDto);            

    } catch (Exception ex) {
        LOGGER.error(ex);
    }
    return json;
}

Then, in Table.jspput the divused in Dialog.jspas hidden, this will be your modaldialog in future (note that there are some changes in the spantags also):

然后,Table.jspdiv所用Dialog.jsphidden,这将是你modal未来的对话框(注意,有在一些变化span标签也):

<div id="BusinessBill" style="display:none;">
    <h2>Bill Details</h2>
    <em>Business Ltd</em>
    <div class="row">
        <span class="spanAsLabel">Account number</span>
        <span id="dlg-account-number" class="spanAsLabel"></span>
    </div>
    <div class="row">
        <span class="spanAsLabel">Bill date</span>
        <span id="dlg-bill-date" class="spanAsLabel"></span>
    </div>
</div>

Now fix your getBusinessBill(..)method like this:

现在getBusinessBill(..)像这样修复你的方法:

You can also use $.ajaxand maybe handle more states like onerrorand others but this way is simpler (at least for me, you just need to evaluate if the returned datais nullor not and let know the user- if null- that something happened at serverside, maybe showing an alertwith a generic message) - please read comments.

您还可以使用$.ajax并可能处理更多类似onerror和其他状态的状态,但这种方式更简单(至少对我而言,您只需要评估返回的data是否是null,并告知user-如果null-server旁边发生了某些事情,可能会显示alert带有通用消息)-请阅读评论。

function getBusinessBill(billReference, billInvoiceDate) {

    $.post("/AccountStatement/businessBill.htm", {
        reference: billReference,
        invoiceDate: billInvoiceDate
    }, function (data) {

        /* You can implement more validations for 'data', in my case I just used these 'if' conditionals but can vary. */

        if(data != null) { //returned 'data' is not 'null'

            /* parse 'data' as 'json' object
             * will be good to console.log(data) and take a look. */
            var obj = $.parseJSON(data);

            if(obj != {}) { //check if 'data' is not an empty 'json' object once transformed

               //set the 'data' in the dialog
               $('#dlg-account-number').text(obj.accountNumber);
               $('#dlg-bill-date').text(obj.billDate);

               /* open modal dialog, you can simulate it this way (for this case)
                * but the correct way is to use 'jquery-ui' dialog or any plugin you prefer.
                * At this point you will see the hidden 'div' in a visible way with your 'data'.
                */
               $('#BusinessBill').fadeIn();
            } else {
               //show 'generic' message
               alert('No results found.');
            }
        } else {
           //show 'generic' message
           alert('An error occurred, try again.');
        }
    });

}

Finally, if everything is correct, you will see at the same page (Table.jsp) the modaldialog with your data, all made by an ajaxcall to avoid redirection pages like (Table.jspto => Dialog.jsp).

最后,如果一切都正确,您将在同一页面 ( Table.jsp) 上看到modal与您的的对话框data,所有这些都是通过ajax调用避免重定向页面 ( Table.jspto => Dialog.jsp) 进行的。