簡體   English   中英

javascript請求動態html而不使用“ window.open()”

[英]javascript request dynamic html without using “window.open()”

我嘗試從動態網頁中提取一些數據(js更改window.onload的內容)。 因此,單個http get請求不足以訪問所需的數據。 有沒有一種方法可以無需在窗口/選項卡中呈現網頁? 我有300個這樣的數據請求,也不想打開300個標簽。

現在我有這個:

 var w = window.open(url, '_blank'); //$.get(url) // cannot be used because the data changes dynamically after beeing loaded (via js) var data setTimeout(function () { var html = w.document.documentElement data = $("smthg", html) w.close() }, 500) 

請注意,我需要延遲數據提取,直到出現“動態”內容為止。

編輯:數據在第三方網頁上。

我假設您嘗試訪問的URL在不同的域上,所以您不能直接使用AJAX。 但是,如果可以使用服務器端腳本語言,則可以做的就是創建自己的代理。

例如使用php:

<?php
// proxy.php

$content = 'File not found.';
$status = 404;

if (isset($_GET['url']) {

  // use curl to get the external URL and put it in a var $content
  $ch = curl_init($_GET['url']);
  curl_setopt(CURLOPT_RETURNTRANSFER, true);
  $content = curl_exec($ch);

  // you could do some error handling here with the status code/content of the response
  // as needed but we will skip all that for now

  if ($content) {
     $status = 200;
  } else {
    $content = 'Error';
    $status = 500;
  } 
}

HttpResponse::status($status);
HttpResponse::setContentType('text/html');
HttpResponse::setData($content);
HttpResponse::send();

現在您可以簡單地向proxy.php發出ajax請求,例如:

var data;
$.get('proxy.php', {url: url}, function (html) {
   data = $("smthg", html);
});

當然,這些URL不在不同的域上,那么您可以直接使用AJAX:

var data;
$.get(url, function (html) {
   data = $("smthg", html);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM