vladislavkopilov

Пример синхронных и ассинхронных запросов

Feb 17th, 2015
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.  
  3. //01) Обычный синхронный ajax get запрос
  4. $.ajax({
  5.     type: "GET",
  6.     url: "/path/path/?promo="+promo+"&code="+code,
  7.     cache: false,
  8.     success: function(html){
  9.       $("#chooseAdd div.content").html(html);    
  10.     }
  11. });
  12.  
  13. //02) Обычный синхроный ajax post запрос
  14. $.post('/path/path/',
  15.  { itemadd : form['itemadd'].value, submitform : form['submitform'].value},
  16.  function(html){
  17.         $("#chooseAdd div.content").html(html);
  18. }, "html");
  19.            
  20. //02.2) Обычный синхроный ajax post запрос 2
  21. $.ajax({
  22.     type: "POST",
  23.     url: '/path/path/',
  24.     cache: false,
  25.     data: { itemadd : form['itemadd'].value, submitform : form['submitform'].value},
  26.     dataType: "html",
  27.     success: function(html) {
  28.         $("#chosseAddForm").html(html);
  29.         return false;  
  30.     }
  31. });
  32.  
  33. //03) Ассинхронные запросы
  34.  
  35.   //необходимые функции
  36.   //01)
  37.   function getRequestStateText(code) {
  38.     switch (code) {
  39.       case 0: return "Uninitialized."; break;
  40.       case 1: return "Loading..."; break;
  41.       case 2: return "Loaded."; break;
  42.       case 3: return "Interactive..."; break;
  43.       case 4: return "Complete."; break;
  44.     }
  45.   }
  46.  
  47.   //02)
  48.   function processRequestChange() {
  49.     var gg = getRequestStateText(request.readyState);
  50.     // если выполнен
  51.     if (request.readyState == 4) {
  52.       // если успешно
  53.       if (request.status == 200) {
  54.         $("#chooseAdd div.content").html(request.responseText);
  55.       } else {
  56.         alert("Не удалось получить данные:n" + request.statusText);
  57.       }
  58.     }
  59.     // иначе, если идет загрузка или в процессе - показываем слой "Загружаются данные"
  60.     else if (request.readyState == 3 || request.readyState == 1) {
  61.     }
  62.   }
  63.  
  64.   //03) для кроссбраузерности
  65.   function getXmlHttp(){
  66.     var xmlhttp;
  67.     try {
  68.       xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  69.     } catch (e) {
  70.       try {
  71.         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  72.       } catch (E) {
  73.         xmlhttp = false;
  74.       }
  75.     }
  76.     if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  77.       xmlhttp = new XMLHttpRequest();
  78.     }
  79.     return xmlhttp;
  80.   }
  81.  
  82.   //Ассинхронный get запрос
  83.   var request = getXmlHttp();
  84.   request.mozBackgroundRequest = true; //for mozzila
  85.   request.onreadystatechange = processRequestChange;
  86.  
  87.   request.open('GET', "/path/path/?promo="+promo+"&code="+code, true); // готовим сам запрос
  88.   request.send(null); // посылаем запрос методом send
  89.   var timeout = setTimeout( function(){ request.abort(); }, 10000);
  90.  
  91.   //Ассинхронный post запрос
  92.   var params = 'itemadd=' + encodeURIComponent(form['itemadd'].value)
  93.       + '&submitform=' + encodeURIComponent(form['submitform'].value);
  94.   var request = getXmlHttp();
  95.   request.mozBackgroundRequest = true;
  96.   request.onreadystatechange = processRequestChange;
  97.   request.open('POST', "/path/path/", true); // готовим сам запрос
  98.   request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //устанавливаем заголовок
  99.   request.send(params); // посылаем запрос методом send
  100.   var timeout = setTimeout( function(){ request.abort(); }, 10000);
Advertisement
Add Comment
Please, Sign In to add comment