web-dev-qa-db-ja.com

XMLHttpRequestクロスドメイン

ページからテキストを抽出するためのこのJavaScriptコードがあります。ドメインでファイルを開くと正常に機能しますが、セキュリティ上の理由から、別のドメインのファイルからテキストを取得できません。だから私の質問は、javascriptで別のウェブサイトからテキストを抽出する方法です。jqueryなしでお願いします。

ありがとうございました

function reqListener () {
  console.log(this.responseText);
}

var xhr = new XMLHttpRequest();

xhr.onload = reqListener;

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://anotherweb.com/datafile.php', true);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send(null);

これを試しましたが、機能しません。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

$(document).ready(function(){
  $("button").click(function(){
    $.ajax({
      url: "http://localhost/index.php",
      dataType : "json",
      contentType: "application/json; charset=utf-8",
      cache: false,
      success: function(response) {
        alert(response);
      },
      error: function (e) {                
      }
      });
  });
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
7
tomsk

Access-Control-Allow-Originヘッダーがdatafile.phpの応答ヘッダーに設定されている場合は機能します:)

リクエストをサーバーに送り返し、必要な場所にリダイレクトできます。

javascript関数:

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();}
else{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;}}
xmlhttp.open("POST","response.php",true);
xmlhttp.send();

.htaccessファイル:

Options +FollowSymLinks
RewriteEngine On
RewriteRule  ^response(.*?)\.php http://example.com/query [R]

Javascript関数は、example.comからの応答をtxtHintdivに書き込みます。

このように書いたのは、これが私のアプリでの使用方法であり、小さな変更のみを行ったためです。それが役に立てば幸い

1
Vegstar

クロスドメインリクエストを行うことはできません。クライアント側(ブラウザ)のセキュリティ問題により、example1.comからexample2.comへXMLHttpRequestまたはjQuery(XMLHttpRequestのラッパー)を介して。これは、CORS(すべてのクライアントブラウザーで利用できるわけではないクロスオリジンリソースシェアリング)を介してHTML5をサポートする最新のブラウザーで効果的に実装できます。したがって、解決策はexample2.comのexample1.comにスクリプトタグを挿入することであり、この解決策は既知です。 JSON-P(パディング付きのJSON)として、データはサーバー(example2.com)によって提供される任意の形式である可能性があるため、名前は誤解を招く可能性があります。その実装コードはこのリンクにあります http:// newtechinfo .net/jsonp-for-cross-domain-ajax /

0
P.Gurung

クロスドメインの制限を回避するには、 postMessage を使用する必要があります。

0
John Henckel