全面解析$.Ajax()方法参数(推荐)

2019-09-14 06:57:31于海丽

17.username

要求为String类型的参数,用于响应HTTP访问认证请求的用户。

18.password

要求为String类型的参数,用于响应HTTP访问认证请求的密码。

19.processData

要求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度来讲而非字符串)以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM树信息或者其他不希望转换的信息,请设置为false。

20.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>';
    });
    $('#resText').html(html);
   }
  });
 });
});

知识链接:

1、$.each()函数:$.each()函数不同于jQuery对象的each()方法,它是一个全局函数,不操作jQuery对象。该函数接收两个参数,第1个参数是一个数组或对象,第2个参数是一个回调函数。回调函数拥有两个参数:第1个参数为数组的索引或对象的成员,第2个参数为对应的变量或内容。

  $.each(data,function(commentIndex,comment){
  //doSomething;
 })

2、ajaxStart()与ajaxStop():当Ajax请求开始时,会触发ajaxStart()方法的回调函数。当Ajax请求结束时,会触发ajaxStop()方法的回调函数。这些方法都是全局的方法,因此无论创建它们的代码位于何处,只要有Ajax请求发生时,就会触发它们。

有时候页面需要加载一些图片,可能速度回比较慢,如果在加载过程中,不给用户提供一些提示和反馈信息,很容易让用户误认为按钮单击无用,使用户对网站失去信息。

此时,我们就需要为网页添加一个提示信息,常用的提示信息是“加载中...”,代码如下:

<div id="loading">加载中...</div>

当Ajax请求开始时,将此元素显示,用来提示用户Ajax请求正在进行;当Ajax请求结束后,将此元素隐藏。代码如下:

$("#loading").ajaxStart(function(){
    $(this).show();
  }).ajaxStop(function(){
 $(this).hide();
 })

好了,下面再给大家分享一个案例代码:

$(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>';
    });
    $('#resText').html(html);
   }
  });
 });
});