我需要执行以下操作:
在粘贴事件中捕获粘贴到简单 HTML 文本框中的 URL,并将其保存到名为 myURL 的 JavaScript 变量(此代码有效)
使用 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/