码迷,mamicode.com
首页 > Web开发 > 详细

[JQuery] Ajax使用过程中的问题总结

时间:2016-04-18 06:29:35      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

JQuery提供的ajax函数,在使用过程中,因为对参数的不了解,导致了很多错误,现在总结如下,以便时常温固,不犯同样的错误。

1、我在项目中使用到的ajax请求格式如下:

 1 $.ajax({
 2                     url:
 3                     data:
 4                     contentType:
 5                     dataType:
 6                     type:
 7                     complete:function(res, textStatus, jqXHR){
 8                         if(textStatus != ‘success‘){
 9 
10                         }
11                     },
12                     error:function(){
13 
14                     },
15                     success:function(res){
16 
17                     }
18                 });

这里出现了3个type,分别是什么意思呢?

第一个contentType,摘录一段stackoverflow上的回答:

contentType (default: ‘application/x-www-form-urlencoded; charset=UTF-8‘)

Type: String

When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it‘ll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server‘s default charset; you must decode this appropriately on the server side.

这个参数设置的是,指定服务器以什么方式解析参数,默认是application/x-www-form-urlencoded; charset=UTF-8,也可以在请求中明确的指出来;另外常用语json对象的参数,contentType也有设置为"application/json"的。

第二个dataType,同样摘录stackoverflow的回答:

dataType (default: Intelligent Guess (xml, json, script, or html))

Type: String

The type of data that you‘re expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

这个参数指定的是,我们希望服务器返回的数据类型,例如,可以不用指定,服务器会自己判断。

第三个type:就是我们以什么请求去发送数据了。有“GET”和“POST”两种。

 

2、服务器返回400错误:400 Bad request,很可能是请求参数有误,例如,需要发送两个参数,但是只发送了一个;或者服务端设置接受数据类型和实际传送的不一致(例如我指定的是contentType:‘application/x-www-form-urlencoded‘,但服务端需要的是contentType:‘application/x-www-form-urlencoded; charset=UTF-8‘)。这样的错误从console里看不出具体原因,需要自己检查是参数哪里不对。

 

[JQuery] Ajax使用过程中的问题总结

标签:

原文地址:http://www.cnblogs.com/bluebirid/p/5403043.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!