将数据从ajax发送到弹簧控制器

时间:2016-10-05 10:16:59

标签: ajax spring-mvc

        var form_data = {
            itemid: globalSourceItem.substr(globalSourceItem.indexOf("-") + 1),
            columnName: jqInputs[0].value,
            displayName: jqInputs[1].value,
            format: jqInputs[2].value,
            KBE: jqInputs[3].value,
            dgroup: jqInputs[4].value,
            dupkey: jqInputs[5].value ,
            measurement: jqInputs[6].value ,
            times: new Date().getTime()
        };
        // console.log(form_data);
        // console.log($("#tourl").html());
        $.ajax({
            url: $("#tourl").html(),
            type: 'POST',
            datatype: 'json',
            data: form_data,
            success: function(message) {
                var j_obj = $.parseJSON(message);
                // console.log(j_obj);return false;
                if (j_obj.hasOwnProperty('success')) {
                    toastr.info('Item updated successfully');
                    setTimeout(function(){
                        window.location.reload();
                    },1000); 
                } else {
                    toastr.info('There was a problem.');
                }
            },
            error: function(xhr, textStatus, errorThrown) 
            {
                toastr.info('There seems to be a network problem. Please try again in some time.');
            }
        });

    }

Hii朋友,这段代码正在为php工作,我需要通过ajax将相同的数据发送到spring mvc,任何人都可以帮我解决在哪里进行更改的确切解决方案,因为我同样怀疑喜欢2周......

1 个答案:

答案 0 :(得分:0)

public class TestController {   
    @RequestMapping(value = "url", method = RequestMethod.POST)
    public ModelAndView action(@RequestBody FormData formData) {
        ...
    }
}

public class FormData { 
   private String itemid;
   public String getItemid() {
       return itemid;
   }
   public void setItemid(String itemid) {
       this.itemid = itemid;
   }    
   //...
}

试试这样的话。您应该能够将JSON对象映射到Java对象。

也许您可以使用注释@ResponseBody并将JSONObject转换为String:

@RequestMapping(value = "/ajax", method = RequestMethod.POST, produces="application/json")
@ResponseBody
public String ajax(@RequestBody ListDataDefinition listDataDefinition) { 
    System.out.println("id="+listDataDefinition.getItemid()); 
    int i=SchemaDAOI.updateldd(listDataDefinition); 
    String message="success"; 
    JSONObject obj = new JSONObject(); 
    try { 
        obj.put("success", "success"); 
    } 
    catch (JSONException e) { 
        e.printStackTrace(); 
    } 
    if(i==1){ 
        System.out.println("success"); 
    } 
    else{ 
        System.out.println("failure"); 
    } 
    return obj.toString(); 
    } 
}

如果将String作为ResponseBody发送到View并将yield设置为JSON,则应将其视为纯JSON RQ。