无法使用 Ajax 调用 Spring 的控制器方法

Can't call Spring's Controller method using Ajax

我是 Ajax 的新手,需要一些帮助。我需要使用 Ajax 调用控制器方法并将输出显示为 JSP 页面上的响应。下面给出的是我试过的一段代码,但我无法让它工作。

服务器代码

@RequestMapping(value="/home.do",method=RequestMethod.POST,params="custdetails")
public  @ResponseBody ModelAndView getCustomderDetails(@RequestParam("str")   String custId,@ModelAttribute("customerdropdown") CustomerNameDropDown cdropdown)
{
    ModelAndView mav = new ModelAndView("CustomerDetails");
    List listCustomerDetails=new ArrayList();
    List<Object[]> CustomerDetailsList = new ArrayList<Object[]>(); 

    CustomerDetailsList=customerDetailsService.getCustomerDetails(custId);

    mav.addObject("custregistration", cdropdown);
    mav.addObject("customerdetailslist", CustomerDetailsList);
    return mav;
}

客户代码

function getCustomerDetails(str) {
    var xmlhttp;

    if (str=="")
    {
        document.getElementById("txtHint").innerHTML="";
        return;
    }

    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();        
    }
    else
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200)
            {
                document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
            }
            else
            {
                document.getElementById("txtHint").innerHTML="Please Enter All Fields..";
            }
        }
    };

    xmlhttp.open("POST","home.do?custdetails"+"&age="+str,true);
    xmlhttp.send(); 
}

您应该在控制器方法中将 @RequestParam("str") 更改为 @RequestParam("age"),请求参数的值是请求参数的名称,在您的情况下是 age xmlhttp.open("POST","home.do?custdetails"+"&age="+str,true);

您可以将请求中的参数名称更改为 xmlhttp.open("POST","home.do?custdetails"+"&str="+str,true);,但我想前者更合适,因为您很可能在映射中混淆了参数名称和参数值

如果您的意图是让 RequestParam 成为可选参数,您应该明确定义它,如 @RequestParam(value="age", required=false) 否则它是强制性的