日常工作中(主要使用ASP.net),我需要编写很多JavaScript代码。我做的最重复的任务之一是jQuery Ajax调用。你看:
$.ajax({
type: "POST",
url: "MyPage.aspx/MyWebMethod",
data: "{parameter:value,parameter:value}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//function called successfull
},
error: function(msg) {
//some error happened
}
});
我不知道对您来说是否相同,但是对我来说用这种语法编写调用太麻烦了。而且,以前必须按照已知规则使用参数构建字符串以传递给WebMethod:字符串必须用引号传递,数字不能传递,等等。
因此,我决定创建一个小而有用的JavaScript类来帮助我有了这个特定的问题,现在我已经完成了jQuery Ajax调用,这对我来说非常友好。
在类构造函数中,我传递页面名称,方法名称以及成功和错误函数。以后,我会根据需要对addParam方法进行尽可能多的调用。最后,我调用run方法进行Ajax调用。成功函数和错误函数必须分别编写。
参数根据其类型进行处理。如果参数是字符串,则使用引号。如果是数字,我不会。日期参数是一种特殊情况。在这种情况下,我使用JavaScript日期对象的getTime()函数,该函数给了我自1970年1月1日以来的日期的毫秒数。后来,我将该值转换为UTC时间,这样我得到了一个最终的毫秒数,即我可以将Int64值传递给我的VB.net(或C#)代码,用它来重建.Net中的日期值。
这是我的jAjax类的完整列表(末尾带有日期帮助器功能):
function jAjax(pageName, methodName, successFunc, errorFunc) {
//stores the page name
this.pageName=pageName;
//stores the method name
this.methodName=methodName;
//stores the success function
this.successFunc=successFunc;
//stores the error function
this.errorFunc=errorFunc;
//initializes the parameter names array
this.paramNames=new Array();
//initializes the parameter values array
this.paramValues=new Array();
//method for add a new parameter (simply pushes to the names and values arrays)
this.addParam=function(name, value) {
this.paramNames.push(name);
this.paramValues.push(value);
}
//method to run the jQuery ajax request
this.run=function() {
//initializes the parameter data string
var dataStr='{';
//iterate thru the parameters arrays to compose the parameter data string
for (var k=0; k < this.paramNames.length; k++) {
//append the parameter name
dataStr +=this.paramNames[k] + ':';
if (typeof this.paramValues[k]=='string') {
//string parameter, append between quotes
dataStr +='"' + this.paramValues[k] + '",';
} else if (typeof this.paramValues[k]=='number') {
//number parameter, append "as-is" calling toString()
dataStr +=this.paramValues[k].toString() + ',';
} else if (typeof this.paramValues[k]=='object') {
if (this.paramValues[k].getTime !=undefined) {
//date value
//call to my getUtcTime function to get the number of
//milliseconds (since january 1, 1970) in UTC format
//and append as a number
dataStr +=getUtcTime(this.paramValues[k]).toString() + ',';
} else {
//object value
//because I don't know what's this, append the toString()
//output
dataStr +='"' + this.paramValues[k].toString() + '",';
}
}
}
//if some parameter added, remove the trailing ","
if (dataStr.length > 1) dataStr=dataStr.substr(0, dataStr.length - 1);
//close the parameter data string
dataStr +='}';
//do the jQuery ajax call, using the parameter data string
//and the success and error functions
$.ajax({
type: "POST",
url: this.pageName + "/" + this.methodName,
data: dataStr,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
successFunc(msg);
},
error: function(msg) {
errorFunc(msg);
}
});
}
}
function getUtcTime(dateValue) {
//get the number of milliseconds since january 1, 1970
var time=dateValue.getTime();
//get the UTC time offset in minutes. if you created your date with
//new Date(), maybe this contains a value. but if you compose the date
//by yourself (i.e. var myDate=new Date(1984,5,21,12,53,11)) this will
//be zero
var minutes=dateValue.getTimezoneOffset() * -1;
//get the milliseconds value
var ms=minutes * 60000;
//add to the original milliseconds value so we get the GMT exact value
return time + ms;
}
这是使用的语法:
var ajaxCall=new jAjax('MyPage.aspx','MyWebMethod',successFunc,errorFunc);
ajaxCall.addParam('s','this is a string');
ajaxCall.addParam('n',34);
ajaxCall.addParam('d',new Date());
ajaxCall.run();
function successFunc(msg) {
...
}
function errorFunc(msg) {
}
另外一个好处是,您可以将成功和错误功能重新用于几个ajax调用。
希望对您有帮助!!随时在您的应用程序中使用jAjax类。
JAX 是一种与服务器交换数据的技术,可以在补充在整个页面的情况下更新网页的一部分。接下来通过本文给大家介绍ajax一些常用方法,大家有需要可以一起学习。
1.url:
要求为String类型的参数,(默认为当前页地址)发送请求的地址。
2.type:
要求为String类型的参数,请求方式(post或get)默认为get。注意其他http请求方法,例如put和delete也可以使用,但仅部分浏览器支持。
3.timeout:
要求为Number类型的参数,设置请求超时时间(毫秒)。此设置将覆盖$.ajaxSetup()方法的全局设置。
4.async:
要求为Boolean类型的参数,默认设置为true,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器,用户其他操作必须等待请求完成才可以执行。
5.cache:
要求为Boolean类型的参数,默认为true(当dataType为script时,默认为false),设置为false将不会从浏览器缓存中加载请求信息。
6.data:
要求为Object或String类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格式。get请求中将附加在url后。防止这种自动转换,可以查看 processData选项。对象必须为key/value格式,例如{foo1:"bar1",foo2:"bar2"}转换为&foo1=bar1&foo2=bar2。如果是数组,JQuery将自动为不同值对应同一个名称。例如{foo:["bar1","bar2"]}转换为&foo=bar1&foo=bar2。
7.dataType:
要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并作为回调函数参数传递。可用的类型如下:
xml:返回XML文档,可用JQuery处理。
html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。
script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求时(不在同一个域下),所有post请求都将转为get请求。
json:返回JSON数据。
jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个“?”为正确的函数名,以执行回调函数。
text:返回纯文本字符串。
8.beforeSend:
要求为Function类型的参数,发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义HTTP头。在beforeSend中如果返回false可以取消本次ajax请求。XMLHttpRequest对象是惟一的参数。
function(XMLHttpRequest){
this; //调用本次ajax请求时传递的options参数
}
9.complete:
要求为Function类型的参数,请求完成后调用的回调函数(请求成功或失败时均调用)。参数:XMLHttpRequest对象和一个描述成功请求类型的字符串。
function(XMLHttpRequest, textStatus){
this; //调用本次ajax请求时传递的options参数
}
10.success:
要求为Function类型的参数,请求成功后调用的回调函数,有两个参数。
(1)由服务器返回,并根据dataType参数进行处理后的数据。
(2)描述状态的字符串。
function(data, textStatus){
//data可能是xmlDoc、jsonObj、html、text等等
this; //调用本次ajax请求时传递的options参数
}
11.error:
要求为Function类型的参数,请求失败时被调用的函数。该函数有3个参数,即XMLHttpRequest对象、错误信息、捕获的错误对象(可选)。ajax事件函数如下:
function(XMLHttpRequest, textStatus, errorThrown){
//通常情况下textStatus和errorThrown只有其中一个包含信息
this; //调用本次ajax请求时传递的options参数
}
12.contentType:
要求为String类型的参数,当发送信息至服务器时,内容编码类型默认为"application/x-www-form-urlencoded"。该默认值适合大多数应用场合。
13.dataFilter:
要求为Function类型的参数,给Ajax返回的原始数据进行预处理的函数。提供data和type两个参数。data是Ajax返回的原始数据,type是调用jQuery.ajax时提供的dataType参数。函数返回的值将由jQuery进一步处理。
function(data, type){
//返回处理后的数据
return data;
}
14.dataFilter:
要求为Function类型的参数,给Ajax返回的原始数据进行预处理的函数。提供data和type两个参数。data是Ajax返回的原始数据,type是调用jQuery.ajax时提供的dataType参数。函数返回的值将由jQuery进一步处理。
function(data, type){
//返回处理后的数据
return data;
}
15.global:
要求为Boolean类型的参数,默认为true。表示是否触发全局ajax事件。设置为false将不会触发全局ajax事件,ajaxStart或ajaxStop可用于控制各种ajax事件。
16.ifModified:
要求为Boolean类型的参数,默认为false。仅在服务器数据改变时获取新数据。服务器数据改变判断的依据是Last-Modified头信息。默认值是false,即忽略头信息。
17.jsonp:
要求为String类型的参数,在一个jsonp请求中重写回调函数的名字。该值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,例如{jsonp:'onJsonPLoad'}会导致将"onJsonPLoad=?"传给服务器。
18.username:
要求为String类型的参数,用于响应HTTP访问认证请求的用户名。
19.password:
要求为String类型的参数,用于响应HTTP访问认证请求的密码。
20.processData:
要求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度来讲并非字符串)以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM树信息或者其他不希望转换的信息,请设置为false。
21.scriptCharset:
要求为String类型的参数,只有当请求时dataType为"jsonp"或者"script",并且type是GET时才会用于强制修改字符集(charset)。通常在本地和远程的内容编码不同时使用。
案例代码:
$(function(){
$('#send').click(function(){
$.ajax({
type: "GET",
url: "test.json",
data: {username:$("#username").val(), content:$("#content").val()},
dataType: "json",
success: function(data){
$('#resText').empty(); //清空resText里面的所有内容
var html='';
$.each(data, function(commentIndex, comment){
html +='<div class="comment"><h6>' + comment['username']
+ ':</h6><p class="para"' + comment['content']
+ '</p></div>';
});
Query的ajax请求
因为是发送 ajax 请求,不是操作DOM
不需要依赖选择器去获取到元素
他的使用是直接依赖 jQuuery 或者 $ 变量来使用
语法:$.ajax( { 本次发送ajax的配置项 } )
配置项
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
$.ajax({
url:'haha.php',
success:function(res){
//res 接受的就是后端给回的相应结果
console.log(res)
},
error:function(){
console.log('请求失败')
}
})
</script>
</body>
</html>
以上就是jQuery的ajax请求了
*请认真填写需求信息,我们会在24小时内与您取得联系。