2016-02-09 9 views
5

私が申請していJS Bootcampのに入るためにプロジェクトをビルドする必要があるのバニラJSのバージョンは何ですか。彼らはバニラのJSだけを使うかもしれないと言います、具体的にはフレームワークとJqueryは許されません。私は、APIからJSONファイルを取得したかったこれまで私は

$.getJSON(url, functionToPassJsonFileTo) 
JSONコールの

$.getJSON(url + "&callback?", functionToPassJsonPFileTo) 

JSONPコールの

を言うでしょう。私はちょうどので、私はJSONまたはJSONPまたはそれらがどのようにAJAXと呼ばれるこの事に関連するとの違いを知らない心に留めてください今月プログラミングを始めました。私がバニラのJavascriptで達成した2行をどのように得るのか説明してください。ありがとうございました。

ので

function jsonp(uri){ 
    return new Promise(function(resolve, reject){ 
     var id = '_' + Math.round(10000 * Math.random()) 
     var callbackName = 'jsonp_callback_' + id 
     window[callbackName] = function(data){ 
      delete window[callbackName] 
      var ele = document.getElementById(id) 
      ele.parentNode.removeChild(ele) 
      resolve(data) 
     } 

     var src = uri + '&callback=' + callbackName 
     var script = document.createElement('script') 
     script.src = src 
     script.id = id 
     script.addEventListener('error', reject) 
     (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script) 
    }) 
} 

は、JSONPと同等となり、明確にしますか?ここで

答えて

16

$.getJSONのためのバニラJSバージョンです:

var request = new XMLHttpRequest(); 
request.open('GET', '/my/url', true); 

request.onload = function() { 
    if (request.status >= 200 && request.status < 400) { 
    // Success! 
    var data = JSON.parse(request.responseText); 
    } else { 
    // We reached our target server, but it returned an error 

    } 
}; 

request.onerror = function() { 
    // There was a connection error of some sort 
}; 

request.send(); 

参考:JSONPについてはhttp://youmightnotneedjquery.com/

はSOすでにあなたはJSONエンコードされたデータをロードすることができます答え$.getJSONhere

を持っています GETのHTTPリクエストを使用してサーバから。

+0

「$ .getJSON()」と同等です(明らかでない場合)。 JSONPの取得は大きく異なります。 – Pointy

+2

そのリンクは非常に便利な資源である、ここでのラインは、ラインの比較である:http://youmightnotneedjquery.com/#json –

+0

しかし、IE8を扱うjqueryの1.xのではありません? –

0

の上の$ .getJSONに相当するバニラjsに感謝しますが、私はまったく同じ点に来ます。私は実際に私がマスターしていないjqueryを取り除こうとしていました。 私は最終的には両方のケースにしてstrugglinてることはJSONリクエストの非同期な性質です。

私は何を達成しようとしていることは非同期呼び出し

function shorten(url){ 

var request = new XMLHttpRequest(); 
bitly="http://api.bitly.com/v3/shorten?&apiKey=mykey&login=mylogin&longURL="; 
request.open('GET', bitly+url, true); 

request.onload = function() { 
    if (request.status >= 200 && request.status < 400) { 
    var data = JSON.parse(request.responseText).data.url; 
    alert ("1:"+data); //alerts fine from within 
    // return data is helpless 
    } 
}; 

request.onerror = function() { 
    // There was a connection error of some sort 
    return url; 
}; 

request.send(); 

} 

から変数を抽出することである今、関数が定義されていることを&は御馳走

shorten("anyvalidURL"); // alerts fine from within "1: [bit.ly url]" 

が、どのように私は割り当てないの作品関数が呼ばれた後、私のJavaScriptでそれを使用できるようにする(非同期呼び出しから)データ値

例えば

のように
document.write("My tiny is : "+data); 
+0

>しかし、どのようにデータ値を(非同期呼び出しから)割り当てるのですか? 'function shorten(url、onSuccess)'のようなコールバック関数を渡してから、onSuccessを結果オブジェクトで呼び出す必要があります。データ – Milli

2

ES6には、グローバルにfetch()というグローバルな方法でリソースを非同期的にフェッチする方法が用意されています。

それはXMLHttpRequestよりも簡単です。

fetch(url) // Call the fetch function passing the url of the API as a parameter 
.then(function() { 
    // Your code for handling the data you get from the API 
}) 
.catch(function() { 
    // This is where you run code if the server returns any errors 
});