之前写过一篇《.NET MVC 异步提交和返回参数》 ,里面有一些ajax的内容,但是不深入,这次详细剖析下jquery中$.ajax的用法。

首先,上代码;

jquery-1.5.1 $.ajax源码:

  1. jQuery.extend({
  2.  
  3. getScript: function( url, callback ) {
  4. return jQuery.get( url, undefined, callback, "script" );
  5. },
  6.  
  7. getJSON: function( url, data, callback ) {
  8. return jQuery.get( url, data, callback, "json" );
  9. },
  10.  
  11. // Creates a full fledged settings object into target
  12. // with both ajaxSettings and settings fields.
  13. // If target is omitted, writes into ajaxSettings.
  14. ajaxSetup: function ( target, settings ) {
  15. if ( !settings ) {
  16. // Only one parameter, we extend ajaxSettings
  17. settings = target;
  18. target = jQuery.extend( true, jQuery.ajaxSettings, settings );
  19. } else {
  20. // target was provided, we extend into it
  21. jQuery.extend( true, target, jQuery.ajaxSettings, settings );
  22. }
  23. // Flatten fields we don't want deep extended
  24. for( var field in { context: 1, url: 1 } ) {
  25. if ( field in settings ) {
  26. target[ field ] = settings[ field ];
  27. } else if( field in jQuery.ajaxSettings ) {
  28. target[ field ] = jQuery.ajaxSettings[ field ];
  29. }
  30. }
  31. return target;
  32. },
  33.  
  34. ajaxSettings: {
  35. url: ajaxLocation,
  36. isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
  37. global: true,
  38. type: "GET",
  39. contentType: "application/x-www-form-urlencoded",
  40. processData: true,
  41. async: true,
  42. /*
  43. timeout: 0,
  44. data: null,
  45. dataType: null,
  46. username: null,
  47. password: null,
  48. cache: null,
  49. traditional: false,
  50. headers: {},
  51. crossDomain: null,
  52. */
  53.  
  54. accepts: {
  55. xml: "application/xml, text/xml",
  56. html: "text/html",
  57. text: "text/plain",
  58. json: "application/json, text/javascript",
  59. "*": "*/*"
  60. },
  61.  
  62. contents: {
  63. xml: /xml/,
  64. html: /html/,
  65. json: /json/
  66. },
  67.  
  68. responseFields: {
  69. xml: "responseXML",
  70. text: "responseText"
  71. },
  72.  
  73. // List of data converters
  74. // 1) key format is "source_type destination_type" (a single space in-between)
  75. // 2) the catchall symbol "*" can be used for source_type
  76. converters: {
  77.  
  78. // Convert anything to text
  79. "* text": window.String,
  80.  
  81. // Text to html (true = no transformation)
  82. "text html": true,
  83.  
  84. // Evaluate text as a json expression
  85. "text json": jQuery.parseJSON,
  86.  
  87. // Parse text as xml
  88. "text xml": jQuery.parseXML
  89. }
  90. },
  91.  
  92. ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
  93. ajaxTransport: addToPrefiltersOrTransports( transports ),
  94.  
  95. // Main method
  96. ajax: function( url, options ) {
  97.  
  98. // If url is an object, simulate pre-1.5 signature
  99. if ( typeof url === "object" ) {
  100. options = url;
  101. url = undefined;
  102. }
  103.  
  104. // Force options to be an object
  105. options = options || {};
  106.  
  107. var // Create the final options object
  108. s = jQuery.ajaxSetup( {}, options ),
  109. // Callbacks context
  110. callbackContext = s.context || s,
  111. // Context for global events
  112. // It's the callbackContext if one was provided in the options
  113. // and if it's a DOM node or a jQuery collection
  114. globalEventContext = callbackContext !== s &&
  115. ( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
  116. jQuery( callbackContext ) : jQuery.event,
  117. // Deferreds
  118. deferred = jQuery.Deferred(),
  119. completeDeferred = jQuery._Deferred(),
  120. // Status-dependent callbacks
  121. statusCode = s.statusCode || {},
  122. // ifModified key
  123. ifModifiedKey,
  124. // Headers (they are sent all at once)
  125. requestHeaders = {},
  126. // Response headers
  127. responseHeadersString,
  128. responseHeaders,
  129. // transport
  130. transport,
  131. // timeout handle
  132. timeoutTimer,
  133. // Cross-domain detection vars
  134. parts,
  135. // The jqXHR state
  136. state = 0,
  137. // To know if global events are to be dispatched
  138. fireGlobals,
  139. // Loop variable
  140. i,
  141. // Fake xhr
  142. jqXHR = {
  143.  
  144. readyState: 0,
  145.  
  146. // Caches the header
  147. setRequestHeader: function( name, value ) {
  148. if ( !state ) {
  149. requestHeaders[ name.toLowerCase().replace( rucHeaders, rucHeadersFunc ) ] = value;
  150. }
  151. return this;
  152. },
  153.  
  154. // Raw string
  155. getAllResponseHeaders: function() {
  156. return state === 2 ? responseHeadersString : null;
  157. },
  158.  
  159. // Builds headers hashtable if needed
  160. getResponseHeader: function( key ) {
  161. var match;
  162. if ( state === 2 ) {
  163. if ( !responseHeaders ) {
  164. responseHeaders = {};
  165. while( ( match = rheaders.exec( responseHeadersString ) ) ) {
  166. responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
  167. }
  168. }
  169. match = responseHeaders[ key.toLowerCase() ];
  170. }
  171. return match === undefined ? null : match;
  172. },
  173.  
  174. // Overrides response content-type header
  175. overrideMimeType: function( type ) {
  176. if ( !state ) {
  177. s.mimeType = type;
  178. }
  179. return this;
  180. },
  181.  
  182. // Cancel the request
  183. abort: function( statusText ) {
  184. statusText = statusText || "abort";
  185. if ( transport ) {
  186. transport.abort( statusText );
  187. }
  188. done( 0, statusText );
  189. return this;
  190. }
  191. };
  192.  
  193. // Callback for when everything is done
  194. // It is defined here because jslint complains if it is declared
  195. // at the end of the function (which would be more logical and readable)
  196. function done( status, statusText, responses, headers ) {
  197.  
  198. // Called once
  199. if ( state === 2 ) {
  200. return;
  201. }
  202.  
  203. // State is "done" now
  204. state = 2;
  205.  
  206. // Clear timeout if it exists
  207. if ( timeoutTimer ) {
  208. clearTimeout( timeoutTimer );
  209. }
  210.  
  211. // Dereference transport for early garbage collection
  212. // (no matter how long the jqXHR object will be used)
  213. transport = undefined;
  214.  
  215. // Cache response headers
  216. responseHeadersString = headers || "";
  217.  
  218. // Set readyState
  219. jqXHR.readyState = status ? 4 : 0;
  220.  
  221. var isSuccess,
  222. success,
  223. error,
  224. response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
  225. lastModified,
  226. etag;
  227.  
  228. // If successful, handle type chaining
  229. if ( status >= 200 && status < 300 || status === 304 ) {
  230.  
  231. // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
  232. if ( s.ifModified ) {
  233.  
  234. if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
  235. jQuery.lastModified[ ifModifiedKey ] = lastModified;
  236. }
  237. if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
  238. jQuery.etag[ ifModifiedKey ] = etag;
  239. }
  240. }
  241.  
  242. // If not modified
  243. if ( status === 304 ) {
  244.  
  245. statusText = "notmodified";
  246. isSuccess = true;
  247.  
  248. // If we have data
  249. } else {
  250.  
  251. try {
  252. success = ajaxConvert( s, response );
  253. statusText = "success";
  254. isSuccess = true;
  255. } catch(e) {
  256. // We have a parsererror
  257. statusText = "parsererror";
  258. error = e;
  259. }
  260. }
  261. } else {
  262. // We extract error from statusText
  263. // then normalize statusText and status for non-aborts
  264. error = statusText;
  265. if( !statusText || status ) {
  266. statusText = "error";
  267. if ( status < 0 ) {
  268. status = 0;
  269. }
  270. }
  271. }
  272.  
  273. // Set data for the fake xhr object
  274. jqXHR.status = status;
  275. jqXHR.statusText = statusText;
  276.  
  277. // Success/Error
  278. if ( isSuccess ) {
  279. deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
  280. } else {
  281. deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
  282. }
  283.  
  284. // Status-dependent callbacks
  285. jqXHR.statusCode( statusCode );
  286. statusCode = undefined;
  287.  
  288. if ( fireGlobals ) {
  289. globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
  290. [ jqXHR, s, isSuccess ? success : error ] );
  291. }
  292.  
  293. // Complete
  294. completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
  295.  
  296. if ( fireGlobals ) {
  297. globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
  298. // Handle the global AJAX counter
  299. if ( !( --jQuery.active ) ) {
  300. jQuery.event.trigger( "ajaxStop" );
  301. }
  302. }
  303. }
  304.  
  305. // Attach deferreds
  306. deferred.promise( jqXHR );
  307. jqXHR.success = jqXHR.done;
  308. jqXHR.error = jqXHR.fail;
  309. jqXHR.complete = completeDeferred.done;
  310.  
  311. // Status-dependent callbacks
  312. jqXHR.statusCode = function( map ) {
  313. if ( map ) {
  314. var tmp;
  315. if ( state < 2 ) {
  316. for( tmp in map ) {
  317. statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
  318. }
  319. } else {
  320. tmp = map[ jqXHR.status ];
  321. jqXHR.then( tmp, tmp );
  322. }
  323. }
  324. return this;
  325. };
  326.  
  327. // Remove hash character (#7531: and string promotion)
  328. // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
  329. // We also use the url parameter if available
  330. s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
  331.  
  332. // Extract dataTypes list
  333. s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
  334.  
  335. // Determine if a cross-domain request is in order
  336. if ( !s.crossDomain ) {
  337. parts = rurl.exec( s.url.toLowerCase() );
  338. s.crossDomain = !!( parts &&
  339. ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
  340. ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
  341. ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
  342. );
  343. }
  344.  
  345. // Convert data if not already a string
  346. if ( s.data && s.processData && typeof s.data !== "string" ) {
  347. s.data = jQuery.param( s.data, s.traditional );
  348. }
  349.  
  350. // Apply prefilters
  351. inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
  352.  
  353. // If request was aborted inside a prefiler, stop there
  354. if ( state === 2 ) {
  355. return false;
  356. }
  357.  
  358. // We can fire global events as of now if asked to
  359. fireGlobals = s.global;
  360.  
  361. // Uppercase the type
  362. s.type = s.type.toUpperCase();
  363.  
  364. // Determine if request has content
  365. s.hasContent = !rnoContent.test( s.type );
  366.  
  367. // Watch for a new set of requests
  368. if ( fireGlobals && jQuery.active++ === 0 ) {
  369. jQuery.event.trigger( "ajaxStart" );
  370. }
  371.  
  372. // More options handling for requests with no content
  373. if ( !s.hasContent ) {
  374.  
  375. // If data is available, append data to url
  376. if ( s.data ) {
  377. s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
  378. }
  379.  
  380. // Get ifModifiedKey before adding the anti-cache parameter
  381. ifModifiedKey = s.url;
  382.  
  383. // Add anti-cache in url if needed
  384. if ( s.cache === false ) {
  385.  
  386. var ts = jQuery.now(),
  387. // try replacing _= if it is there
  388. ret = s.url.replace( rts, "$1_=" + ts );
  389.  
  390. // if nothing was replaced, add timestamp to the end
  391. s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
  392. }
  393. }
  394.  
  395. // Set the correct header, if data is being sent
  396. if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
  397. requestHeaders[ "Content-Type" ] = s.contentType;
  398. }
  399.  
  400. // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
  401. if ( s.ifModified ) {
  402. ifModifiedKey = ifModifiedKey || s.url;
  403. if ( jQuery.lastModified[ ifModifiedKey ] ) {
  404. requestHeaders[ "If-Modified-Since" ] = jQuery.lastModified[ ifModifiedKey ];
  405. }
  406. if ( jQuery.etag[ ifModifiedKey ] ) {
  407. requestHeaders[ "If-None-Match" ] = jQuery.etag[ ifModifiedKey ];
  408. }
  409. }
  410.  
  411. // Set the Accepts header for the server, depending on the dataType
  412. requestHeaders.Accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
  413. s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
  414. s.accepts[ "*" ];
  415.  
  416. // Check for headers option
  417. for ( i in s.headers ) {
  418. jqXHR.setRequestHeader( i, s.headers[ i ] );
  419. }
  420.  
  421. // Allow custom headers/mimetypes and early abort
  422. if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
  423. // Abort if not done already
  424. jqXHR.abort();
  425. return false;
  426.  
  427. }
  428.  
  429. // Install callbacks on deferreds
  430. for ( i in { success: 1, error: 1, complete: 1 } ) {
  431. jqXHR[ i ]( s[ i ] );
  432. }
  433.  
  434. // Get transport
  435. transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
  436.  
  437. // If no transport, we auto-abort
  438. if ( !transport ) {
  439. done( -1, "No Transport" );
  440. } else {
  441. jqXHR.readyState = 1;
  442. // Send global event
  443. if ( fireGlobals ) {
  444. globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
  445. }
  446. // Timeout
  447. if ( s.async && s.timeout > 0 ) {
  448. timeoutTimer = setTimeout( function(){
  449. jqXHR.abort( "timeout" );
  450. }, s.timeout );
  451. }
  452.  
  453. try {
  454. state = 1;
  455. transport.send( requestHeaders, done );
  456. } catch (e) {
  457. // Propagate exception as error if not done
  458. if ( status < 2 ) {
  459. done( -1, e );
  460. // Simply rethrow otherwise
  461. } else {
  462. jQuery.error( e );
  463. }
  464. }
  465. }
  466.  
  467. return jqXHR;
  468. },
  469.  
  470. // Serialize an array of form elements or a set of
  471. // key/values into a query string
  472. param: function( a, traditional ) {
  473. var s = [],
  474. add = function( key, value ) {
  475. // If value is a function, invoke it and return its value
  476. value = jQuery.isFunction( value ) ? value() : value;
  477. s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
  478. };
  479.  
  480. // Set traditional to true for jQuery <= 1.3.2 behavior.
  481. if ( traditional === undefined ) {
  482. traditional = jQuery.ajaxSettings.traditional;
  483. }
  484.  
  485. // If an array was passed in, assume that it is an array of form elements.
  486. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
  487. // Serialize the form elements
  488. jQuery.each( a, function() {
  489. add( this.name, this.value );
  490. } );
  491.  
  492. } else {
  493. // If traditional, encode the "old" way (the way 1.3.2 or older
  494. // did it), otherwise encode params recursively.
  495. for ( var prefix in a ) {
  496. buildParams( prefix, a[ prefix ], traditional, add );
  497. }
  498. }
  499.  
  500. // Return the resulting serialization
  501. return s.join( "&" ).replace( r20, "+" );
  502. }
  503. });

Jquery的$.ajax的用法:

jQuery.ajax( options ) : 通过 HTTP 请求加载远程数据,这个是jQuery 的底层 AJAX 实现。简单易用的高层实现见 $.get, $.post 等。

  $.ajax() 返回其创建的 XMLHttpRequest 对象。大多数情况下你无需直接操作该对象,但特殊情况下可用于手动终止请求。

  注意: 如果你指定了 dataType 选项,请确保服务器返回正确的MIME信息,(如xml返回"text/xml")。错误的MIME类型可能导致不可预知的错误。见Specifying the Data Type for AJAX Requests 。

当设置 datatype 类型为 'script' 的时候,所有的远程(不在同一个域中)POST请求都回转换为GET方式。

  $.ajax() 只有一个参数:参数 key/value 对象,包含各配置及回调函数信息。详细参数选项见下。

  jQuery 1.2 中,您可以跨域加载 JSON 数据,使用时需将数据类型设置为 JSONP。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。数据类型设置为 "jsonp" 时,jQuery 将自动调用回调函数。(这个我不是很懂)

jquery ajax 参数列表:

url(String)

(默认: 当前页地址) 发送请求的地址。

type(String)

请求方式 (参数有两种 "POST" 和 "GET"),默认为 "GET"。注意:其它 HTTP 请求方法,如 PUT 和 DELETE 也可以使用,但仅部分浏览器支持。

timeout(Number)

设置请求超时时间(毫秒)。此设置将覆盖全局设置。

async(Boolean)

(默认: true) 设置为true的情况下所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。

beforeSend(Function)

发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。XMLHttpRequest 对象是唯一的参数。

  1. function(XMLHttpRequest){
  2.  
  3. this; // the options for this ajax request
  4.  
  5. }

cache(Boolean)

是否将请求结果设置缓存(默认: true) ,设置为 false 将不会从浏览器缓存中加载请求信息,注意开发初期最好设置为false,否则不方便调试的哦。

complete(Function)

请求完成后回调函数 (请求成功或失败时均调用)。参数: XMLHttpRequest 对象,成功信息字符串。

  1. function(XMLHttpRequest,textStatus){
  2.  
  3. this;//theoptionsforthisajaxrequest
  4.  
  5. }

contentType(String)

(默认: "application/x-www-form-urlencoded") 发送信息至服务器时内容编码类型。默认值适合大多数应用场合。

data(Object,String)

发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2'。

dataType(String)

定义服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息返回 responseXML 或 responseText,并作为回调函数参数传递,可用值:

"xml": 返回 XML 格式数据,可用 jQuery 处理。

"html": 返回纯文本 HTML 格式数据;可包含 script 元素。

"script": 返回纯文本 JavaScript 代码。不会自动缓存结果。

"json": 返回 JSON 数据 。

"jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。

error(Function)

(默认: 自动判断 (xml 或 html)) 请求失败时将调用此方法。这个方法有三个参数:XMLHttpRequest 对象,错误信息,(可能)捕获的错误对象。

  1. function(XMLHttpRequest,textStatus,errorThrown){
  2.  
  3. //通常情况下textStatus和errorThown只有其中一个有值
  4.  
  5. this;//theoptionsforthisajaxrequest
  6.  
  7. }

global(Boolean)

是否触发全局 AJAX 事件(默认: true) 。设置为 false 将不会触发全局 AJAX 事件,如 ajaxStart 或 ajaxStop 。可用于控制不同的Ajax事件

ifModified(Boolean)

(默认: false) 仅在服务器数据改变时获取新数据。使用 HTTP 包 Last-Modified 头信息判断。

processData(Boolean)

设置发送数据的信息格式(默认: true),设置为 true 的时候发送的数据将被转换为对象(技术上讲并非字符串) 以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。

success(Function)

请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态

  1. function(data,textStatus){
  2.  
  3. //datacouldbexmlDoc,jsonObj,html,text,etc...
  4.  
  5. this;//theoptionsforthisajaxrequest
  6.  
  7. }

下面以一则示例解释一下该方法的具体的用法:

  1. $.ajax({
  2.  
  3. type:'get',
  4.  
  5. url:'http://www.www.daimajiayuan.com/rss',
  6.  
  7. beforeSend:function(XMLHttpRequest){
  8.  
  9. //ShowLoading();
  10.  
  11. },
  12.  
  13. success:function(data,textStatus){
  14.  
  15. $('.ajax.ajaxResult').html('');
  16.  
  17. $('item',data).each(function(i,domEle){
  18.  
  19. $('.ajax.ajaxResult').append('<li>'+$(domEle).children('title').text()+'</li>');
  20.  
  21. });
  22.  
  23. },
  24.  
  25. complete:function(XMLHttpRequest,textStatus){
  26.  
  27. //HideLoading();
  28.  
  29. },
  30.  
  31. error:function(){
  32.  
  33. //请求出错处理
  34.  
  35. }
  36.  
  37. });

Jquery的$.post的用法:

jQuery.post( url, [data], [callback], [type] ) :使用POST方式来进行异步请求

jquery $.post 方法参数列表(说明):

url (String) : 发送请求的URL地址.

data (Map) : (可选) 要发送给服务器的数据,以 Key/value 的键值对形式表示,可将此值放到url中。

callback (Function) : (可选) 载入成功时回调函数(只有当Response的返回状态是success才能调用该方法)。

type (String) : (可选)客户端请求的数据类型(JSON,XML,等等)

这是一个简单的 POST 请求功能以取代复杂 $.ajax ,请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。

下面是一个使用$.post的简单示例代码:

  1. $.post(
  2.  
  3. 'http://www.daimajiayuan.com/ajax.php',
  4.  
  5. {Action:"post",Name:"lulu"},
  6.  
  7. function(data,textStatus){
  8.  
  9. //data可以是xmlDoc,jsonObj,html,text,等等.
  10.  
  11. //this;//这个Ajax请求的选项配置信息,请参考jQuery.get()说到的this
  12.  
  13. alert(data.result);
  14.  
  15. },
  16.  
  17. "json"//这里设置了请求的返回格式为"json"
  18.  
  19. );

如果你设置了请求的格式为"json",此时你没有设置Response回来的ContentType 为:Response.ContentType = "application/json"; 那么你将无法捕捉到返回的数据。

注意,上面的示例中 alert(data.result); 由于设置了Accept报头为"json",这里返回的data就是一个对象,因此不需要用eval()来转换为对象。

Jquery中.ajax和.post详解的更多相关文章

  1. JQuery中$.ajax()方法参数详解

    url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...

  2. JQuery中$.ajax()方法参数详解 及 async属性说明

    url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...

  3. JQuery中$.ajax()方法参数详解(转载)

    url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...

  4. 转:JQuery中$.ajax()方法参数详解

    url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...

  5. (转)JQuery中$.ajax()方法参数详解

    url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...

  6. Jquery中$.ajax()方法参数详解(转)

    转自:http://blog.sina.com.cn/doctor830619 url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数, ...

  7. JQuery中$.ajax()方法参数详解及应用

    url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...

  8. JQuery中$.ajax()方法参数详解 (20

    url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...

  9. JQuery中$.ajax()方法参数详解 转载

    url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...

随机推荐

  1. tar软件安装

    安装tar   ./configure   make   sudo make install

  2. 防止基本的XSS攻击 滤掉HTML标签

    /** * 防止基本的XSS攻击 滤掉HTML标签 * 将HTML的特殊字符转换为了HTML实体 htmlentities * 将#和%转换为他们对应的实体符号 * 加上了$length参数来限制提交 ...

  3. AJAX实现三级联动

    省市区三级联动插件: 主页面:为方便使用,不用写过多代码,只写一个id为sanji的div,若别的页面要用,只需写一个id为sanji的div,加载上jQuery与sanji.js文件即可 <! ...

  4. time函数计算时间

    学过C语言的都知道有个time函数可以计算时间, 也好像知道time(NULL)返回的是一个距离1970年1月1日0时0分0秒的秒数. #include <stdio.h> #includ ...

  5. webpack基础配置

    webpack运行规则: Webpack 会给每个模块分配一个唯一的id并通过这个id索引和访问模块.在页面启动时,会先执行入口文件中的代码,其它模块会在运行 require 的时候再执行. 运行时主 ...

  6. java常用日期操作方法

    package com.wujiangpo.test.util; import java.text.ParseException; import java.text.SimpleDateFormat; ...

  7. 自定义美化UL OL发光列表

    在线演示 本地下载

  8. hadoop实战项目:查找相同字母组成的字谜

    前面我们学习了MapReduce编程思想和编程示例,那么本节课程同学们一起操练操练,动手完成下面的项目. 项目需求 一本英文书籍包含成千上万个单词或者短语,现在我们需要在大量的单词中,找出相同字母组成 ...

  9. Django详解之四、cookie和session

    一.使用背景 思路 简单的后台管理:对人员的管理 1. 登录注册 2. 老师 班级管理 学院管理 3. 增删改查 开发: 1. 定义数据库表结构 a) 表结构关系 i. class classes(m ...

  10. 20145222黄亚奇 《网络对抗技术》 MAL_逆向与Bof基础

    学习目的 通过一些方法,使能够运行本不该被运行的代码部分,或得到shell的使用: 将正常运行代码部分某处call后的目标地址,修改为另一部分我们希望执行.却本不应该执行的代码部分首地址(这需要我们有 ...