使用JQuery/AAJX/PHP从另一个URL抓取并显示web内容


Scrape and display web content from another URL using JQuery/AJAX/PHP

我需要执行以下操作:

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

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

index.html:

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

URLonspaste.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>

URLonspast.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));