2017-09-04 14 views
-1

我有一个填充下拉列表的ajax代码,我使用mvc c#。 当我从ajax调用我的方法,并且我没有参数的方向栏中有一个url代码工作正常,但如果我在方向栏中的url中有一个参数,这不起作用,并出现此错误: “{readyState: 4,getResponseHeader:ƒ,getAllResponseHeaders:ƒ,setRequestHeader:ƒ,overrideMimeType:ƒ,...}“。当url中有参数时出现Ajax错误

这里是我的代码:

$.ajax({ 
    url:"../Records/myList", 
    type: "POST", 
    dataType: 'json', 
    contentType: 'application/json', 
    // data: JSON.stringify(Data), 
    success: function (resul) { 
     Function(resul); 
    }, 
    error: function (message) { 
    } 
}); 

我的网址:http://localhost:123/Record/EditRecord - >>所以它的工作原理

我的其他网址:http://localhost:123/Record/EditRecord/1 - >>它不喜欢这种

在此先感谢工作。

+0

两者的URL相同。什么是你得到的错误 –

+0

对不起,我已经编辑了第二个网址。谢谢。 – MCarmona

+1

'http:// localhost:123/Record/EditRecord/1' =>此请求是否转到GET方法?我知道如何使用'$ .ajax'来使用各种HTTP方法,但我需要确定你想要使用什么方法。 –

回答

0

从给定的第二个URL(这是行不通的)我假设你想用HttpGet方法使用jQuery AJAX。

http://localhost:123/{controller}/{action}/{id} 

id视为UrlParameter:URL模式与这个路径相符。

因此就需要使用操作参数&数据表示URL的参数值,如下例所示:

控制器

[HttpGet] 
public ActionResult EditRecord(int id) 
{ 
    // other stuff 
} 

视图(JS)

$.ajax({ 
    url: "/Record/EditRecord", 
    type: "GET", 
    dataType: 'json', // response type 
    contentType: 'application/x-www-form-urlencoded; charset=utf-8', // header content type 
    data: { id: 1 }, 
    processData: true, // this is important to use in GET methods 
    success: function (result) { 
     Function(result); 
    }, 
    error: function (message) { 
     // throw error 
    } 
}); 

替代地直接使用URL参数适用于GET方法而不指定data内容:

视图(JS)

$.ajax({ 
    url: "Record/EditRecord/1", 
    type: "GET", 
    processData: true, // this is important to use in GET methods 
    success: function (result) { 
     Function(result); 
    }, 
    error: function (message) { 
     // throw error 
    } 
}); 

NB:使用jQuery.get简化版本:

$.get("/Record/EditRecord/1", function (result) { 
      Function(result); 
     }, "json").error(function (message) { // throw error 
     }); 

PS:这是HTTP的示例POST请求,如果你正在寻找适当的POST方法与AJAX。

控制器

[HttpPost] 
public ActionResult EditRecord(Record rec) 
{ 
    // other stuff 
} 

视图(JS)

$.ajax({ 
    url: "/Record/EditRecord", 
    type: "POST", 
    dataType: 'json', // response type 
    contentType: 'application/json; charset=utf-8', // header content type 
    data: JSON.stringify({ rec: { id: 1, name: 'XXXX', ... }}), 
    success: function (result) { 
     Function(result); 
    }, 
    error: function (message) { 
     // throw error 
    } 
}); 

参考:

Do GET, POST, PUT, DELETE in ASP.NET MVC with jQuery AJAX

0

我看不到代码中的任何错误,但我建议尝试让帕拉姆来与它的名字在服务器或者如果您选择使用(Ajax的功能)的数据属性格式:

{key1: 'value1', key2: 'value2'} 

,或者你使用字符串查询:

page?name=ferret&color=purple 

bacuse你刚才说第一个方法是工作,我假设没有必要检查POST/GET方法。

编辑:

BE奖this

相关问题