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

标签 javascript php jquery html ajax

我需要执行以下操作:

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

关于javascript - 使用 JQuery/AJAX/PHP 从另一个 URL 抓取并显示 Web 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23300155/

相关文章:

javascript 隔离字符

php - 在php中的mysql语句中连接4个表

php - PHP:注意:未定义索引

javascript - 如何在鼠标悬停在第三个 div 上时显示两个 div

javascript - 通过node js在客户端打开新的浏览器选项卡

javascript - 未捕获的语法错误 : missing ) after argument list

javascript - jQuery 与附加数据交互

javascript - 如何打印动态跨度类值?

javascript - 这是有效的 json 数据吗?

php - Codeigniter:构造部分 View 的最佳方式