【问题标题】:Get response after form submit?表单提交后得到响应?
【发布时间】:2017-05-10 10:03:06
【问题描述】:

我有一个我用下面的 html 代码定义的表单:

<form id="addUser" method="post" action=@Url.RouteUrl("DefaultApi", new {controller = "User", action = "Add", httproute = "true"})>

我也有提交按钮:

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

当我点击按钮时,浏览器会转到 api url,但我只是想从 api 中获取价值并将其传递到页面上的 href。

我怎样才能做到?

【问题讨论】:

  • 您可以通过 jquery 执行此操作 .. 在 jquery 中单击按钮调用您的 api 并从您的 api 获取返回值并更新您的 href ...

标签: javascript jquery html asp.net-mvc razor


【解决方案1】:

根据您在问题中提供的信息,我假设您的 Web api 端点接受表单数据并返回您的页面应重定向到的新 url。

您可以使用 jQuery 劫持表单提交事件,使用 ajax 发送数据,一旦您从 web 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

【讨论】:

    【解决方案2】:

    除了 Daniyals 答案,传递输入值:

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

    然后使用以下行进行 ajax 调用:

    data:data,
    

    【讨论】:

      【解决方案3】:

      首先删除输入元素中的表单标签和类型=提交。然后在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 
         }
       });
      });
      

      希望这会有所帮助...

      【讨论】:

      • 您不应该建议删除表单元素。如果 OP 将表单输入值发送到 API 端点怎么办?保留表单元素还可以确保在客户端关闭 JS 时正确提交
      • 并且url需要用“”包裹
      猜你喜欢
      • 2011-03-11
      • 1970-01-01
      • 2013-10-13
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多