javascript之使用 JQuery/AJAX/PHP 从另一个 URL 抓取并显示 Web 内容

txw1958 阅读:41 2026-10-07 19:25:01 评论:0

我需要执行以下操作:

  1. 在粘贴事件中捕获粘贴到简单 HTML 文本框中的 URL,并将其保存到名为 myURL 的 JavaScript 变量(此代码有效)

  2. 使用 AJAX 将 myURL 变量发送到 PHP 页面,该页面将从 URL 中抓取一些内容。 PHP页面(webscraper.php)会将抓取的内容保存在数据库中,然后也在HTML页面(文本框所在的位置)上显示抓取的内容,而无需重新加载页面。这一步就是代码丢失和损坏的地方。

index.html:

<body> 
     <input type="text" class="newslinkinput"/> 
</body> 

URLonpaste.js:

$(document).ready(function () { 
 $(".newslinkinput").bind('paste', function (e) { 
     setTimeout(function () { 
         var myURL = $(".newslinkinput").val() 
         $.ajax({ 
             type: "POST", 
             url: "webscraper.php", 
             data: "newslink=" + myURL.val(), 
             success: function (data) {} 
         }); 
     }, 0); 
   }); 
 }); 

webscraper.php:

<?php    
$newslink = $_POST['newslink']; 
 
require_once('ExternalScraper.php'); 
 
$result = ExternalScraper::fetch($newslink); 
 
$contentA = $result->contentA; 
$contentB = $result->contentB; 
 
include "include/database.php"; 
 
$insert = mysqli_query($connect, "INSERT INTO mytable (contentA, contentB) VALUES ('$contentA', '$contentB')"); 
 
mysqli_close($connect); 
 
//Somehow get $contentA and $contentB to display on index.html 
//Do all this without refreshing the page 
 
?>  

请您参考如下方法:

试试这个:

index.html:

<body> 
     <input type="text" class="newslinkinput"/> 
     <div id="contentA"></div> 
     <div id="contentB"></div> 
</body> 

URLonpaste.js:

... 
$.ajax({ 
    type: "POST", 
    url: "webscraper.php", 
    data: "newslink=" + myURL.val(), 
    dataType: "json", 
    success: function (data) { 
        $('#contentA').html(data.contentA); 
        $('#contentB').html(data.contentB); 
    } 
}); 
... 

webscraper.php(附加到末尾):

... 
echo json_encode(array('contentA' => $contentA, 'contentB' => $contentB)); 


标签:ajax
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号