2016-12-25 114 views
0

我有下面的HTML代碼中定義的一種形式:表單提交後獲得回覆?

<form id="addUser" method="post" [email protected]("DefaultApi", new {controller = "User", action = "Add", httproute = "true"})> 

我也有提交按鈕:

<input type="submit" class="btn btn-primary" value="Add user" /> 

當我點擊按鈕的瀏覽器訪問API URL,但我只是魔杖從api獲取價值並將其過渡到頁面上的href。

我該如何做到這一點?

+0

您可以通過jQuery的做..打電話給你上的按鈕,點擊API中的jQuery和從API獲得的返回值和更新您的href ... –

回答

0

首先刪除表單標籤並在輸入元素中輸入type = submit。然後在javascript

$(button).click(function(){ 
$.ajax({ 
    type:'POST', 
    url:/api/User/Add or /User/Add 
    success: function(declare parameter that will contain value returned by api) 
    { 
    // update your href here using the above parameter 
    } 
}); 
}); 

希望這有助於...

+0

你不應該建議刪除表單元素。如果OP將窗體輸入值發送到API端點,該怎麼辦?保持表單元素也確保在客戶端關閉JS時正確提交 – Terry

+0

無需刪除類型提交,添加一個event.preventDefault(); ... –

+0

而url需要包裹在「」 –

0

加成Daniyals答案,通過輸入值:

data={}; 
$("input").each(function(elem){ 
data[elem.name]=elem.value; 
}); 

然後做下面的行Ajax調用:

data:data, 
0

根據你提供的問題信息,我假設你的web api終點接受表單數據並返回頁面應該重定向到的新url。

您可以使用jQuery劫持表單提交事件,用ajax發送數據,一旦你從你的網絡API調用(新的URL)的反應,用它來設置location.href屬性,這樣的新值瀏覽器將發出一個新的GET請求。

你必須確保你阻止了正常的表單提交行爲。你可以使用jQuery的preventDefault方法來做到這一點。

$(function(){ 
    $("[type='submit']").click(function(e){ 
    e.preventDefault(); 
    var _formUrl=$(this).attr("action"); 
    //make the ajax call now. 
    //Build an object which matches the structure of our view model class 
    var model = { Name: "Shyju", Id: 123 }; 
    //update the above line with data read from your form. 
    $.ajax({ 
     type: "POST", 
     data: JSON.stringify(model), 
     url: _formUrl, 
     contentType: "application/json" 
    }).done(function(res) {  
     console.log('res', res); 
     // Do something with the result :) 
     window.location.href=res; 
    }); 

    }); 

}); 

而且看看How to pass json POST data to Web API method as object