如何使用$.ajax?当我使用它时,它没有击中我的控制器操作
任何人都可以帮助我吗?
我有这段代码
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function GOTO() {
var datastring = "id=2";
$.ajax({
type: "POST",
url: "/Home/Index",
dataType: "json",
data: datastring,
success: function (json) { Complete(json.result); },
error: function (request, status, error) {
//alert("an error occurred: " + error);
alert("Error saving data. Please contact support.");
}
});
}
function Complete(result) {
if (result == "success") {
alert("Success");
}
else {
alert("Failed");
}
}
</script>
<input type="button" value="submit" onclick="JavaScript:GOTO()" />
</asp:Content>
,我的控制器代码是这样的,
[HttpPost]
public System.Web.Mvc.JsonResult Index(string datastring)
{
return Json(new { foo = "bar", baz = "Blech" });
}
但它根本没有击中我的控制器,这是我在视图中做错的事情吗?
谢谢
Can any body help me out.
I have this code
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function GOTO() {
var datastring = "id=2";
$.ajax({
type: "POST",
url: "/Home/Index",
dataType: "json",
data: datastring,
success: function (json) { Complete(json.result); },
error: function (request, status, error) {
//alert("an error occurred: " + error);
alert("Error saving data. Please contact support.");
}
});
}
function Complete(result) {
if (result == "success") {
alert("Success");
}
else {
alert("Failed");
}
}
</script>
<input type="button" value="submit" onclick="JavaScript:GOTO()" />
</asp:Content>
and My Controller Code is this
[HttpPost]
public System.Web.Mvc.JsonResult Index(string datastring)
{
return Json(new { foo = "bar", baz = "Blech" });
}
But it never hits my controller at all, is that Something I am doing wrong in my View?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试像这样传递
数据
:Try passing the
data
like this:您的代码中有语法错误。
此外,您不需要在
onclick
属性中指定JavaScript:
协议,您只需在该位置定义一个标签即可。更好的是,根本不要在 HTML 属性中分配事件侦听器,而是使用不显眼的 JavaScript,包括在 JavaScript 不可用的罕见情况下进行后备。更新:如果您收到“
$.ajax
未定义”错误,则您的页面中可能没有包含 jQuery。 将使用$.ajax
(或任何其他 jQuery 函数)的script
元素添加到页面上方。
You have a syntax error in your code.
Moreover, you don't need to specify the
JavaScript:
protocol in theonclick
attribute, you're merely defining a label at that place. Even better, don't assign event listeners in HTML attributes at all, but use unobtrusive JavaScript, including a fallback for the rare case when JavaScript is unavailable.Update: if you get the "
$.ajax
is undefined" error, you probably didn't include jQuery in your page. AddTo your page above the
script
element that uses$.ajax
(or any other jQuery function).这可能取决于您传入的数据。您的方法需要一个名为 datastring 的参数,但您传入的是“id=2”。
it could be down to what data you are passing in. Your method expects a parameter called datastring but you are passing in 'id=2'.