2016-12-25 52 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