2017-02-01 211 views
-1

我想做一個XMLHttpRequest,但是,我有問題。即使返回false或使用e.preventDefault(),頁面也會自動刷新。我試圖讓城市最終通過一個選項塊。 (我已經啓動了選項部分,並在找出獲取請求問題後完成它。)我正在嘗試使用純Javascript來做到這一點,因爲我已經使用Angular和Node來完成它了。任何幫助,將不勝感激。遇到麻煩製作XMLHttpRequest()

HTML:

<form id="citySearchForm" method="get" onSubmit="return searchFormFunc();"> 
     <div> 
      <p>Choose a city:</p> 
      <input type="text" placeholder="Enter a city" id="getCitiesInput" name="city"> 
      <input type="submit" value="submit"> 
     </div> 
     <div id="weather"></div 
     <p><span id="temp"></span></p 
     <p><span id="wind"></span></p> 
</form> 

的Javascript:

var citySearch = document.getElementById("citySearchForm"); 

// citySearch.addEventListener("submit", searchFormFunc); 

function searchFormFunc(e){ 

    cityName = document.getElementById('getCitiesInput').value; 

    var searchCityLink = "http://autocomplete.wunderground.com/aq?query="; 
    var search = searchCityLink.concat(cityName); 

    console.log("link : " + search); 

    var xhr = XMLHttpRequest(); 

    xhr.onreadystatechange = function() { 
     if(xhr.readyState == 4) { 
      var r = JSON.parse(xhr.response || xhr.responseText); // IE9 has no property response, so you have to use responseText 

      console.log(r); 
     } else { 
      console.log('error'); 
     } 
    }; 

    xhr.open("GET", link, true); 
    xhr.send(null); 

    var r = JSON.parse(xhr.response); 

    return false; 

// e.preventDefault(); 
} 
+0

首先,在html你在innerHTML中追加的是inco rrect。見選項標籤。請注意,如果js中存在錯誤,表單會自動提交。你需要表格嗎?因爲您無論如何都是從Ajax提交 – Ibu

+0

這裏是如何正確使用[Ajax](http://idiallo.com/javascript/ajax-without-jquery) – Ibu

回答

0

您指定您希望這是一個異步請求。所以你需要解析你的迴應onreadystatechangeonload

function ajax(url, callback) { 
    var xhr; 

    if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest(); 
    else { 
     var versions = ["MSXML2.XmlHttp.5.0", 
         "MSXML2.XmlHttp.4.0", 
         "MSXML2.XmlHttp.3.0", 
         "MSXML2.XmlHttp.2.0", 
         "Microsoft.XmlHttp"] 

     for(var i = 0, len = versions.length; i < len; i++) { 
      try { 
       xhr = new ActiveXObject(versions[i]); 
       break; 
      } 
      catch(e){} 
     } // end for 
    } 

    /** Here you can specify what should be done **/ 
    xhr.onreadystatechange = function() { 
     if(xhr.readyState < 4) { 
      return; 
     } 

     if(xhr.status !== 200) { 
      return; 
     } 

     // all is well 
     if(xhr.readyState === 4) { 
      callback(xhr); 
     }   
    } 

    xhr.open('GET', url, true); 
    xhr.send(''); 
} 

從文檔回答user6123921

-1
  1. 你必須使用var xhr = new XMLHttpRequest();
  2. 你定義一個onreadystatechange事件偵聽器
xhr.onreadystatechange = function() { 
     if(xhr.readyState == 4) { 
      var r = JSON.parse(xhr.response || xhr.responseText); // IE9 has no property response, so you have to use responseText 

      console.log(r); 

      /* do stuff with response */ 
     } 
    }; 
+0

爲什麼我得到了一個downvote呢? – NonPolynomial