質問

する必要があります HTTP GET JavaScript でリクエストします。そのための最良の方法は何でしょうか?

これを Mac OS X ダッシュコード ウィジェットで行う必要があります。

役に立ちましたか?

解決

ブラウザ(およびDashcode)は、JavaScriptからHTTPリクエストを行うために使用できるXMLHttpRequestオブジェクトを提供します:

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

ただし、同期リクエストは推奨されておらず、次の行に沿って警告が生成されます。

  

注:Gecko 30.0(Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27)以降、ユーザーエクスペリエンスへの悪影響のため、メインスレッドでの同期リクエストは廃止されました

非同期リクエストを作成し、イベントハンドラー内でレスポンスを処理する必要があります。

function httpGetAsync(theUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}

他のヒント

jQueryで

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);

上記のすばらしいアドバイスはたくさんありますが、あまり再利用できず、DOMナンセンスや簡単なコードを隠す他の綿毛でいっぱいになりすぎます。

これは、再利用可能で使いやすい、作成したJavascriptクラスです。現在、GETメソッドしかありませんが、それは私たちにとってはうまくいきます。 POSTを追加しても、誰かのスキルに負担がかかることはありません。

var HttpClient = function() {
    this.get = function(aUrl, aCallback) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function() { 
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                aCallback(anHttpRequest.responseText);
        }

        anHttpRequest.open( "GET", aUrl, true );            
        anHttpRequest.send( null );
    }
}

使用方法は次のとおりです。

var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
    // do something with response
});

コールバックのないバージョン

var i = document.createElement("img");
i.src = "/your/GET/url?params=here";

新しい window.fetch APIは、ES6 Promiseを利用する XMLHttpRequest のよりクリーンな代替です。 ここには良い説明がありますが、要約すると(記事から):

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function() {
  console.log("Booo");
});

ブラウザのサポートは、最新リリース(Chrome、Firefox、Edge(v14 )、Safari(v10.1)、Opera、Safari iOS(v10.3)、Androidブラウザー、Chrome for Android)。ただし、IEは正式なサポートを受けられません。 GitHubにはポリフィルがあります。これは、主にまだ使用されている古いブラウザをサポートするために推奨されます(3月より前のSafariバージョン2017年と同時期のモバイルブラウザ)。

これがjQueryやXMLHttpRequestよりも便利かどうかは、プロジェクトの性質に依存すると思います。

仕様へのリンク https://fetch.spec.whatwg.org/

編集

ES7 async / awaitを使用すると、これは単純になります( this Gist に基づく):

async function fetchAsync (url) {
  let response = await fetch(url);
  let data = await response.json();
  return data;
}

JavaScriptで直接実行するコードを次に示します。ただし、前述のように、JavaScriptライブラリを使用する方がはるかに優れています。私のお気に入りはjQueryです。

以下のケースでは、JavaScript JSONオブジェクトを返すためにASPXページ(貧乏人のRESTサービスとしてサービスを提供しています)が呼び出されています。

var xmlHttp = null;

function GetCustomerInfo()
{
    var CustomerNumber = document.getElementById( "TextBoxCustomerNumber" ).value;
    var Url = "GetCustomerInfoAsJson.aspx?number=" + CustomerNumber;

    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = ProcessRequest;
    xmlHttp.open( "GET", Url, true );
    xmlHttp.send( null );
}

function ProcessRequest() 
{
    if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) 
    {
        if ( xmlHttp.responseText == "Not found" ) 
        {
            document.getElementById( "TextBoxCustomerName"    ).value = "Not found";
            document.getElementById( "TextBoxCustomerAddress" ).value = "";
        }
        else
        {
            var info = eval ( "(" + xmlHttp.responseText + ")" );

            // No parsing necessary with JSON!        
            document.getElementById( "TextBoxCustomerName"    ).value = info.jsonData[ 0 ].cmname;
            document.getElementById( "TextBoxCustomerAddress" ).value = info.jsonData[ 0 ].cmaddr1;
        }                    
    }
}

コピーアンドペースト可能なバージョン

let request = new XMLHttpRequest();
request.onreadystatechange = function () {
    if (this.readyState === 4) {
        if (this.status === 200) {
            document.body.className = 'ok';
            console.log(this.responseText);
        } else if (this.response == null && this.status === 0) {
            document.body.className = 'error offline';
            console.log("The computer appears to be offline.");
        } else {
            document.body.className = 'error';
        }
    }
};
request.open("GET", url, true);
request.send(null);

IEはロードを高速化するためにURLをキャッシュしますが、たとえば、新しい情報を取得しようとする間隔でサーバーをポーリングしている場合、IEはそのURLをキャッシュし、常に同じデータセットを返します持っていた。

GETリクエストの実行方法(バニラJavaScript、Prototype、jQueryなど)に関係なく、キャッシュと戦うためのメカニズムを確実に配置してください。それに対抗するには、ヒットするURLの末尾に一意のトークンを追加します。これは次の方法で実行できます。

var sURL = '/your/url.html?' + (new Date()).getTime();

これにより、URLの末尾に一意のタイムスタンプが追加され、キャッシュが発生しなくなります。

短くて純粋:

const http = new XMLHttpRequest()

http.open("GET", "https://api.lyrics.ovh/v1/toto/africa")
http.send()

http.onload = () => console.log(http.responseText)

プロトタイプにより、非常にシンプルになります

new Ajax.Request( '/myurl', {
  method:  'get',
  parameters:  { 'param1': 'value1'},
  onSuccess:  function(response){
    alert(response.responseText);
  },
  onFailure:  function(){
    alert('ERROR');
  }
});

Mac OS Dashcode Widgetsには慣れていませんが、JavaScriptライブラリを使用して、をサポートできる場合XMLHttpRequests jQuery を使用して、このようなことをします:

var page_content;
$.get( "somepage.php", function(data){
    page_content = data;
});

古いブラウザをサポートする 1 つのソリューション:

function httpRequest() {
    var ajax = null,
        response = null,
        self = this;

    this.method = null;
    this.url = null;
    this.async = true;
    this.data = null;

    this.send = function() {
        ajax.open(this.method, this.url, this.asnyc);
        ajax.send(this.data);
    };

    if(window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
    }
    else if(window.ActiveXObject) {
        try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP.6.0");
        }
        catch(e) {
            try {
                ajax = new ActiveXObject("Msxml2.XMLHTTP.3.0");
            }
            catch(error) {
                self.fail("not supported");
            }
        }
    }

    if(ajax == null) {
        return false;
    }

    ajax.onreadystatechange = function() {
        if(this.readyState == 4) {
            if(this.status == 200) {
                self.success(this.responseText);
            }
            else {
                self.fail(this.status + " - " + this.statusText);
            }
        }
    };
}

多少やりすぎかもしれませんが、このコードを使用すれば間違いなく安全です。

使用法:

//create request with its porperties
var request = new httpRequest();
request.method = "GET";
request.url = "https://example.com/api?parameter=value";

//create callback for success containing the response
request.success = function(response) {
    console.log(response);
};

//and a fail callback containing the error
request.fail = function(error) {
    console.log(error);
};

//and finally send it away
request.send();

ウィジェットのInfo.plistファイルで、 AllowNetworkAccess キーをtrueに設定することを忘れないでください。

AJAXを使用するのが最善の方法です(このページで簡単なチュートリアルを見つけることができます Tizag )。その理由は、使用する他の手法にはより多くのコードが必要であるため、やり直しなしでクロスブラウザで動作することは保証されておらず、データを解析して閉じるURLを渡すフレーム内の非表示ページを開くことにより、より多くのクライアントメモリを使用する必要があるためです AJAXは、この状況に対処する方法です。私の2年間のjavascriptの重い開発と言えば。

AngularJs を使用している場合、 $ http .get

$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

HTTP GETリクエストは2つの方法で取得できます:

  1. このアプローチはxml形式に基づいています。リクエストのURLを渡す必要があります。

    xmlhttp.open("GET","URL",true);
    xmlhttp.send();
    
  2. これはjQueryに基づいています。呼び出すURLとfunction_nameを指定する必要があります。

    $("btn").click(function() {
      $.ajax({url: "demo_test.txt", success: function_name(result) {
        $("#innerdiv").html(result);
      }});
    }); 
    
function get(path) {
    var form = document.createElement("form");
    form.setAttribute("method", "get");
    form.setAttribute("action", path);
    document.body.appendChild(form);
    form.submit();
}


get('/my/url/')

投稿リクエストでも同じことができます。
このリンクをご覧くださいフォーム送信のようなJavaScript投稿リクエスト

これを行うには、JavaScript Promiseを使用するFetch APIが推奨されるアプローチです。 XMLHttpRequest(XHR)、IFrameオブジェクト、またはダイナミックタグは、古い(そして不格好な)アプローチです。

<script type=“text/javascript”> 
    // Create request object 
    var request = new Request('https://example.com/api/...', 
         { method: 'POST', 
           body: {'name': 'Klaus'}, 
           headers: new Headers({ 'Content-Type': 'application/json' }) 
         });
    // Now use it! 

   fetch(request) 
   .then(resp => { 
         // handle response }) 
   .catch(err => { 
         // handle errors 
    }); </script>

これは素晴らしい fetchデモおよび MDNドキュメント

単純な非同期リクエスト:

function get(url, callback) {
  var getRequest = new XMLHttpRequest();

  getRequest.open("get", url, true);

  getRequest.addEventListener("readystatechange", function() {
    if (getRequest.readyState === 4 && getRequest.status === 200) {
      callback(getRequest.responseText);
    }
  });

  getRequest.send();
}

ダッシュボードウィジェットのコードを使用し、作成したすべてのウィジェットにJavaScriptライブラリを含めたくない場合、SafariがネイティブでサポートするオブジェクトXMLHttpRequestを使用できます。

Andrew Hedgesが報告したように、ウィジェットはデフォルトではネットワークにアクセスできません。ウィジェットに関連付けられているinfo.plistの設定を変更する必要があります。

約束でjoannからのベストアンサーを更新するには、これが私のコードです:

let httpRequestAsync = (method, url) => {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.onload = function () {
            if (xhr.status == 200) {
                resolve(xhr.responseText);
            }
            else {
                reject(new Error(xhr.responseText));
            }
        };
        xhr.send();
    });
}

純粋なJSでもできます:

// Create the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}

// Make the actual CORS request.
function makeCorsRequest() {
 // This is a sample server that supports CORS.
 var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';

var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}

// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
alert('Response from CORS request to ' + url + ': ' + text);
};

xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};

xhr.send();
}

参照:詳細については、 html5rocksチュートリアル

これは、ファイルをオブジェクトとしてロードし、オブジェクトとしてプロパティに非常に高速にアクセスするためのxmlファイルの代替です。

  • 注意、javascriptで彼がコンテンツを正しく解釈できるようにするには、HTMLページと同じ形式でファイルを保存する必要があります。 UTF 8を使用する場合、ファイルをUTF8などで保存します。

XMLはツリーとして機能しますか?書く代わりに

     <property> value <property> 

次のような単純なファイルを作成します。

      Property1: value
      Property2: value
      etc.

ファイルを保存します.. ここで関数を呼び出します....

    var objectfile = {};

function getfilecontent(url){
    var cli = new XMLHttpRequest();

    cli.onload = function(){
         if((this.status == 200 || this.status == 0) && this.responseText != null) {
        var r = this.responseText;
        var b=(r.indexOf('\n')?'\n':r.indexOf('\r')?'\r':'');
        if(b.length){
        if(b=='\n'){var j=r.toString().replace(/\r/gi,'');}else{var j=r.toString().replace(/\n/gi,'');}
        r=j.split(b);
        r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});
        r = r.map(f => f.trim());
        }
        if(r.length > 0){
            for(var i=0; i<r.length; i++){
                var m = r[i].split(':');
                if(m.length>1){
                        var mname = m[0];
                        var n = m.shift();
                        var ivalue = m.join(':');
                        objectfile[mname]=ivalue;
                }
            }
        }
        }
    }
cli.open("GET", url);
cli.send();
}

これで、効率的に値を取得できます。

getfilecontent('mesite.com/mefile.txt');

window.onload = function(){

if(objectfile !== null){
alert (objectfile.property1.value);
}
}

これは、グループに貢献するためのちょっとした贈り物です。ありがとうございます:)

PCで機能をローカルでテストする場合は、次のコマンドを使用してブラウザーを再起動します(safariを除くすべてのブラウザーでサポートされています):

yournavigator.exe '' --allow-file-access-from-files
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top