jquery ajax content type,ajax - Jquery - How to make $.post() use contentType=application/json? - St...

I know this is a late answer, I actually have a shortcut method that I use for posting/reading to/from MS based services.. it works with MVC as well as ASMX etc...

Use:

$.msajax(

'/services/someservice.asmx/SomeMethod'

,{} /*empty object for nothing, or object to send as Application/JSON */

,function(data,jqXHR) {

//use the data from the response.

}

,function(err,jqXHR) {

//additional error handling.

}

);

//sends a json request to an ASMX or WCF service configured to reply to JSON requests.

(function ($) {

var tries = 0; //IE9 seems to error out the first ajax call sometimes... will retry up to 5 times

$.msajax = function (url, data, onSuccess, onError) {

return $.ajax({

'type': "POST"

, 'url': url

, 'contentType': "application/json"

, 'dataType': "json"

, 'data': typeof data == "string" ? data : JSON.stringify(data || {})

,beforeSend: function(jqXHR) {

jqXHR.setRequestHeader("X-MicrosoftAjax","Delta=true");

}

, 'complete': function(jqXHR, textStatus) {

handleResponse(jqXHR, textStatus, onSuccess, onError, function(){

setTimeout(function(){

$.msajax(url, data, onSuccess, onError);

}, 100 * tries); //try again

});

}

});

}

$.msajax.defaultErrorMessage = "Error retreiving data.";

function logError(err, errorHandler, jqXHR) {

tries = 0; //reset counter - handling error response

//normalize error message

if (typeof err == "string") err = { 'Message': err };

if (console && console.debug && console.dir) {

console.debug("ERROR processing jQuery.msajax request.");

console.dir({ 'details': { 'error': err, 'jqXHR':jqXHR } });

}

try {

errorHandler(err, jqXHR);

} catch (e) {}

return;

}

function handleResponse(jqXHR, textStatus, onSuccess, onError, onRetry) {

var ret = null;

var reterr = null;

try {

//error from jqXHR

if (textStatus == "error") {

var errmsg = $.msajax.defaultErrorMessage || "Error retreiving data.";

//check for error response from the server

if (jqXHR.status >= 300 && jqXHR.status < 600) {

return logError( jqXHR.statusText || msg, onError, jqXHR);

}

if (tries++ < 5) return onRetry();

return logError( msg, onError, jqXHR);

}

//not an error response, reset try counter

tries = 0;

//check for a redirect from server (usually authentication token expiration).

if (jqXHR.responseText.indexOf("|pageRedirect||") > 0) {

location.href = decodeURIComponent(jqXHR.responseText.split("|pageRedirect||")[1].split("|")[0]).split('?')[0];

return;

}

//parse response using ajax enabled parser (if available)

ret = ((JSON && JSON.parseAjax) || $.parseJSON)(jqXHR.responseText);

//invalid response

if (!ret) throw jqXHR.responseText;

// d property wrap as of .Net 3.5

if (ret.d) ret = ret.d;

//has an error

reterr = (ret && (ret.error || ret.Error)) || null; //specifically returned an "error"

if (ret && ret.ExceptionType) { //Microsoft Webservice Exception Response

reterr = ret

}

} catch (err) {

reterr = {

'Message': $.msajax.defaultErrorMessage || "Error retreiving data."

,'debug': err

}

}

//perform final logic outside try/catch, was catching error in onSuccess/onError callbacks

if (reterr) {

logError(reterr, onError, jqXHR);

return;

}

onSuccess(ret, jqXHR);

}

} (jQuery));

NOTE: I also have a JSON.parseAjax method that is modified from json.org's JS file, that adds handling for the MS "/Date(...)/" dates...

The modified json2.js file isn't included, it uses the script based parser in the case of IE8, as there are instances where the native parser breaks when you extend the prototype of array and/or object, etc.

I've been considering revamping this code to implement the promises interfaces, but it's worked really well for me.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值