[英]AJAX and PHP sending “HTTP get request” to the same page
My application gathers some client related information via JavaScript and submits it via AJAX to a php page. 我的应用程序通过JavaScript收集了一些与客户端相关的信息,并通过AJAX将其提交到php页面。
See the code below: 请参见下面的代码:
index.php index.php
<html>
<head>
<script>
function postClientData(){
var client_data = new Array(screen.availHeight, screen.availWidth);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == client_data[0]){
document.getElementById("message").innerHTML = "Client data successfully submitted!";
}
}
};
var parameters = "ajax.php?screen_height=" + client_data[0] + "&screen_width=" + client_data[1];
xmlhttp.open("GET", parameters, true);
xmlhttp.send();
}
</script>
</head>
<body onload="postClientData()">
<span id="message"></span></p>
</body>
</html>
ajax.php ajax.php
<?php
echo $_REQUEST["screen_height"];
//Does something else...
?>
I was wondering if I could merge the ajax.php content to my index.php and eliminate ajax.php. 我想知道是否可以将ajax.php内容合并到我的index.php中并消除ajax.php。 When I try adding the code, I probably get into a endless loop since I don't get my "success" message. 当我尝试添加代码时,由于未收到“成功”消息,可能会陷入无限循环。
How can I solve this issue? 我该如何解决这个问题?
Correct, IMO I would definitely keep this specific logic separated in the ajax.php
file. 正确,IMO,我一定会将这种特定的逻辑放在ajax.php
文件中。
If you do really want to merge, add it to the top of index.php (before printing data): 如果确实要合并,则将其添加到index.php的顶部(在打印数据之前):
if (isset($_GET['screen_height'])) && isset($_GET['screen_width']) {
// Execute specific logic and exit to prevent sending the HTML.
exit;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.