2015-09-16 109 views
0

希望有人可以用这个指向正确的方向,整天都在挠头,并且正在开发一个秃头斑。我花了很多时间,但是我发现的问题中没有一个似乎与我的确切问题有关。MVC AJAX POST请求重定向到原始页面作为GET

简而言之,我有一个下拉列表,并希望让用户能够实时向列表中添加条目。我打算使用AJAX将表单信息发送给控制器,然后将其输入到表中,重新查询,然后作为JSON数组返回到页面,然后我将解析它并替换Select下拉列表中的数据。

但是,会发生POST请求,并且在数据处理过程中的某个时间点刷新页面,并将数据作为GET请求附加到URL。

Ajax请求:(!以防万一)

$(document).on("click", "#save-new-range", function (e) { 
    e.preventDefault; 

    var loc = window.location.href; 
    var url = stripURL('Data/addRange', loc); // Format the target URL correctly 

    $.post(url, $("#add-range-form").serialize()) 
     .done(function (response) { 
      debugger; 
      alert(response); 
    }); 
}); 

StripURL功能

function stripURL(url, loc) { 
var res = ""; 

if (loc.search("Surveys/New") !== -1) { 
    res = loc.replace("Surveys/New", ""); 
} else if (loc.search("Surveys/Amend") !== -1) { 
    res = loc.replace("Surveys/Amend", ""); 
} else if (loc.search("Surveys/") !== -1) { 
    res = loc.replace("Surveys/Amend", ""); 
} 


if (res.search("#") !== -1) { 
    res = res.replace("#", ""); 
} 

url = res + url; 

return url; 
} 

的控制器(没有查询和插入):

[HttpPost] 
public JsonResult addRange(FormCollection fc) 
{ 
    { 
    ... Do data processing and query data into a dictionary called res ... 
    } 
    return Json(res); 
} 

调试,我控制器操作被处理并且res被填充正确的数据,但.done()函数从不输入d重新定向。

很高兴发布完整的控制器,但为了简洁起见,我已经将其留出。让我知道你是否想看到它。

+0

尝试在你的.on文件中添加一个'return false'(按下http://stackoverflow.com/questions/7524971/jquery-post-refreshes-my-page – tofutim

+0

试试'preventDefault()'在最后调用'()'。 – area28

回答

1
$(document).on("click", "#save-new-range", function (e) { 
    e.preventDefault; 

    var loc = window.location.href; 
    var url = stripURL('Data/addRange', loc); // Format the target URL correctly 

    $.post(url, $("#add-range-form").serialize()) 
     .done(function (response) { 
      debugger; 
      alert(response); 
    }); 

    return false; 
}); 

看看这是否有窍门。

+0

是的,它做到了。整天为了两个小小的话,我的头撞到了一堵砖墙上!非常感谢你给我解释, – Funk247

2

您正在使用e.preventDefault而未将其作为函数调用。这不会运行。这就是为什么return false;在接受的答案中工作。使用e.preventDefault()作为函数调用不需要return false;

$(document).on("click", "#save-new-range", function (e) { 

    // called as a function 
    e.preventDefault(); 

    var loc = window.location.href; 
    var url = stripURL('Data/addRange', loc); // Format the target URL correctly 

    $.post(url, $("#add-range-form").serialize()) 
     .done(function (response) { 
      debugger; 
      alert(response); 
    }); 
}); 

您可以在SO这样控制台测试:

$('a').click(function(e){ 
    e.preventDefault(); 
}); 

这将阻止任何a标签从它的默认行为。如果你忽略了函数调用,它什么也不做。

+0

谢谢澄清,我会确保这将在未来考虑到。 – Funk247

相关问题