2017-09-04 55 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

相關問題