ajax 根据从 URL 发送的 Json 对象执行操作

ajax performs actions based on Json object sent from URL

我正在学习 Ajax,但不确定 Ajax 是否可以处理我的用例。 我有一个带有按钮的模板(Spring MVC 中的 JSP 文件)。 我目前的设计是,如果用户点击按钮,he/she 将被重定向到另一个页面

        $('#Button').on('click',function() {
      location.href = "/fulfill/order/${orderID}";
    });

现在,我想将我的控制器 /fulfill/order/${orderID} 重新设计为 return Json 对象。 所以如果用户现在点击按钮,控制器仍然会被调用并且 returns Json 对象。因此 Ajax 可以捕获那些 Json 对象并根据此控制器发送的 Json 对象执行操作。 例如,如果用户单击按钮,控制器 return 将 Json 对象 "successful" 和 Ajax 处理此 Json 对象并显示图像;如果控制器 return 是 Json 对象 "error, can not fulfill",Ajax 处理此 Json 对象并显示弹出错误消息。

我如何使用 Ajax 来完成这个任务。这可能吗?

$.get("/fulfill/order/${orderID}",{},function(response){
     console.log(response);

})

如果您的控制器的操作仅接受 POST 请求:

$.post("/fulfill/order/${orderID}",{},function(response){
     console.log(response);

}) ; 

如果您想传递更多参数(即:"/fulfill/order/${orderID}"?id=4343&before=2016),您需要将第 2n 个参数 {} 替换为 {id:4343,before:2016}


$.get&$.post来简化$.ajax调用。但是,如果您想设置 AJAX 的自定义参数,建议使用 $.ajax 调用:

    $.ajax({
        type : "POST",
        contentType : "application/json",
        url : "/fulfill/order/${orderID}",
        data : JSON.stringify(data),
        dataType : 'json',
        timeout : 100000,
        success : function(data) {
            console.log("SUCCESS: ", data);
            display(data);
        },
        error : function(e) {
            console.log("ERROR: ", e);
            display(e);
        },
        done : function(e) {
            console.log("DONE");
        }
    });

一个很好的教程 here 可以处理 Spring MVC+AJAX

的许多用例