2011-11-05 52 views
0

我有以下幾點:我可以使用jQuery簡化這個ajax調用嗎?

$.ajax({ 
    type: "POST", 
    traditional: true, 
    url: "/Administration/Locations/DoAction", 
    data: { partitionKey: id.substring(14), 
      rowKey: id.substring(4, 14), 
      action: ac, 
      datastore: $("#DataSource").val() 
    }, 
    async: false, 
    dataType: "json", 
    timeout: 1000, 
    success: function (data) { 
     xx 
    }, 
    error: function (x, t, m) { 
     xx 
    } 

可以,我可以使用jQuery使後簡化這個?請注意,id和ac是較早分配的javascript變量。

+1

簡化什麼辦法嗎?這是非常簡單的代碼,但可能會在其他代碼的上下文中進行更改。你能解釋一下你的問題嗎? – Bojangles

+1

你想簡化一下嗎?看起來相當原始/簡單。 – Shomz

+2

'async:false'擊敗了ajax的目的。 – AlienWebguy

回答

0
$.ajaxSetup({async:false}); 
$.post("/Administration/Locations/DoAction", 
    { partitionKey: id.substring(14), 
      rowKey: id.substring(4, 14), 
      action: ac, 
      datastore: $("#DataSource").val() 
    }, 
    function (data) { 
     xx 
    }, 
    "json" 
).error(function() { 
    xx 
}); 

文檔http://api.jquery.com/jQuery.post/

$.post()是相同

$.ajax({ 
    type: 'POST', 
    url: url, 
    data: data, 
    success: success, 
    dataType: dataType 
}); 
+0

遺漏了異步。 –

+0

看起來不錯。我只是看看這個鏈接,看看我可以如何設置異步:false。在這種情況下我需要這個。 –

+0

請參閱我的新答案 – Peter

0

根據您的應用程序,你可能能夠使用一個全局的ErrorHandler和/或successhandler。但最有可能的只有第一個。結合彼得的回答,你應該很好走。要設置這些全球處理程序使用

$.ajaxError(...) 
$.ajaxSuccess(...) 

請參閱http://api.jquery.com/jQuery.ajaxSetup/。列表中列出了所有全局ajaxHandler初始化程序的列表。

0

檢查,如果這對你的作品:

$.ajax({ 
type: "POST", 
traditional: !0, 
url: "/Administration/Locations/DoAction", 
data: { 
    partitionKey: id.substring(14), 
    rowKey: id.substring(4, 14), 
    action: ac, 
    datastore: $("#DataSource") 
     .val() 
}, 
async: !1, 
dataType: "json", 
timeout: 1e3, 
success: function() {}, 
error: function() {} 
}) 
相關問題