簡體   English   中英

ajax根據從URL發送的Json對象執行操作

[英]ajax performs actions based on Json object sent from URL

我現在正在學習Ajax,不確定Ajax是否可以處理我的用例。 我有一個帶有按鈕的模板(Spring MVC中的JSP文件)。 我當前的設計是,如果用戶單擊該按鈕,他/她將被重定向到另一個頁面

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

現在,我想重新設計控制器/fulfill/order/${orderID}以返回Json對象。 因此,如果用戶現在單擊按鈕,控制器仍將被調用並返回Json對象。 因此,Ajax可以捕獲這些Json對象並根據此控制器發送的Json對象執行操作。 例如,如果用戶單擊按鈕,則控制器返回Json對象“成功”,並且Ajax處理該Json對象並顯示圖像; 如果控制器返回Json對象“錯誤,無法實現”,則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 ),則需要將{} {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");
        }
    });

一個很好的教程可以處理Spring MVC + AJAX的許多用例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM