[英]Trying to call a PHP script in separate JS file, how do i display the output onto my HTML page
First time trying this can anyone help me, i get an output on the console but have no idea how to display it in a tag.第一次尝试这个可以帮助我,我在控制台上得到一个输出,但不知道如何在标签中显示它。 This is the problem for both the sections of my code.
这是我的代码的两个部分的问题。 Any help would be appreciated.
任何帮助,将不胜感激。
const URL_GETOFFERS = 'getOffers.php';
const URL_GETOFFERS_XML = 'getOffers.php?useXML';
fetch(URL_GETOFFERS)
.then(
function (response) {
return response.text();
})
.then(
function (data) {
console.log(data);
document.getElementById("getHTMLOffer").innerHTML = "<p>" + this.responseText + "</p>";
})
.catch(
function (err) {
console.log("Something went wrong!", err);
});
fetch(URL_GETOFFERS_XML)
.then(
function (response) {
return response.text();
})
.then(
function (data) {
console.log(data);
parser = new DOMParser();
xmlDoc = parser.parseFromString(data,"text/xml");
xmlDoc.getElementsById("getXMLOffer").innerHTML = this.responseText;
})
.catch(
function (err) {
console.log("Something went wrong!", err);
});
});
If you want to put some content inside HTML elements you have to:如果您想在 HTML 元素中放置一些内容,您必须:
<div id="getHTMLOffer">initial content</div>
<div id="getXMLOffer">initial content</div>
get
the elements in Javascript, after DOM has loadedget
Javascript 中的元素 // the contents of this function is executed after the HTML structure (DOM) is loaded
// aka `on ready`
(function() {
document.getElementById("getHTMLOffer").innerHTML = "new content here";
document.getElementById("getXMLOffer").innerHTML = "new content here";
})();
Know that there are multiple ways to accomplish this.知道有多种方法可以实现这一点。 Above is shown just one of those ways.
以上只是其中一种方式。
Also be aware the function getElementById
gets only one element.另请注意,函数
getElementById
仅获取一个元素。 In your code there is a typo getElementsById
(extra s
character).在您的代码中有一个拼写错误
getElementsById
(额外s
字符)。
A rudimentary example that sends a basic GET request with a querystring to the same page, processes th servers response and displays on the page将带有查询字符串的基本 GET 请求发送到同一页面、处理服务器响应并显示在页面上的基本示例
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['task'] ) ){
ob_clean();
echo 'Some text as respons to the FETCH request task = "'.$_GET['task'].'"';
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>FETCH</title>
</head>
<body>
<aside id='getHTMLOffer'></aside>
<script>
fetch( '?task=fetch&source=text' )
.then( r=>{ return r.text() } )
.then( data=>{
document.getElementById('getHTMLOffer').innerHTML=data
})
.catch(err=>{ alert( err ) } )
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.