![](/img/trans.png)
[英]Why XmlHttpRequest readyState = 2 on 200 HTTP response code
[英]Why xmlhttprequest response is in html code
出于某种原因,当我使用 xmlhttp 发送 http 请求时,我得到的答案是 html 形式
function HttpRequest(method, url, username, password) {
const xhr = new XMLHttpRequest();
let received_data;
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responsejson);
if (xhr.responseText == "access granted")
console.log("ok");
else
console.log("error");
}
}
xhr.open(method, url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send('username=' + username + '&password=' + password);
xhr.onload = function() {
console.log("connected to " + url);
}
}
function send_data() {
let method = 'POST';
let url = 'https://localhost:83/android_app/server.php'; //url of the php
server(must be https:// (secure) in order to make the connection using cordova app)
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
HttpRequest(method, url, username, password)
}
还有我发送此请求的 php 服务器:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
header('Access-Control-Allow-Origin: *');
$name = $_POST['username'];
$password = $_POST['password'];
if($name=="admin" && $password=="1234"){
echo "access granted";
}
else{
echo "access denit";
}
?>
</body>
</html>
这是我得到的回应
您可以将通过 AJAX 调用的 function 想象成一个子例程。 它应该只返回调用者想要的。 目前所有 HTML 都被发送回 AJAX 呼叫以及授予的access granted
,因此很难找到您想要的东西。
因此,如果您将server.php
代码更改为
<?php
header('Access-Control-Allow-Origin: *');
$name = $_POST['username'];
$password = $_POST['password'];
if($name=="admin" && $password=="1234"){
echo "access granted";
}else{
echo "access denit";
}
您将返回给 AJAX 调用的所有内容是access granted
或access denit
,这是您在 javascript 中测试的内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.