javascript - 为什么 URL 未定义(在 JQuery Ajax 发布之后)

标签 javascript jquery asp.net ajax

基本上,我在个人资料 View 中执行 Ajax 发布后尝试刷新 View 。

 $.ajax({ 
     url: '/Profile/Index',
     dataType: "html", 
     type: "POST", 
     data: JSON.stringify(10), 
     success: function(returl) { 
         alert('It worked'); 
         window.location.href = returl.url;
     }, 
     error: function(jqXHR,responseText,textStatus) {
         alert(jqXHR.responseText) 
     } 
});

这是 HttpPost 操作:

[HttpPost]
public ActionResult Index(string number){
    //Things to do
    var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Profile");
    return Json(new { Url = redirectUrl });
}

发布后我得到这个 URL:http://localhost:50738/undefined 我已经调试了 Controller 方法并且它正确地获取了/Profile。我不明白为什么这个问题一直存在...谢谢!

最佳答案

您告诉 Ajax 请求期望返回 HTML 而不是 JSON,因此 returl 完全是一个字符串值,因此 returl.url 将是未定义的。将您的数据类型更改为 json。

http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings 上找到这个.查看数据类型参数以获取更多信息。

$.ajax({
        url: '/Profile/Index',
        dataType: "json",
        type: "POST",
        data: JSON.stringify(10),
        success: function (returl) {
            alert('It worked');
            window.location.href = returl.Url;
        },
        error: function (jqXHR, responseText, textStatus) {
            alert(jqXHR.responseText);
        }
    });

关于javascript - 为什么 URL 未定义(在 JQuery Ajax 发布之后),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31612816/

相关文章:

javascript - node.js:是否可以在服务器端 html 响应中传递 jQuery 代码?

asp.net - 服务堆栈 :Type definitions should start with a '{' , 期望序列化类型 'AuthResponse' ,得到以以下开头的字符串

javascript - 覆盖浏览器 "Find"功能

javascript - 如何创建包含 php + Javascript 变量的 href 链接

javascript - 如何在 HTML 元素中显示和隐藏数组的每个项目?

c# - 带有链接按钮的 ASP.net Visual Studio Repeater

c# - 在 C# 中不使用 GDI+ 处理图像

javascript - setTimeout 和 clearTimeout 中断

javascript - 无法使用 JS FormData 对象发布视频文件输入

javascript - 正则表达式 - 检查多个模式是否适用于字符串