出于某種原因,當我使用 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>
這是我得到的回應

uj5u.com熱心網友回復:
您可以將通過 AJAX 呼叫的函式想象成一個子例程。它應該只回傳呼叫者想要的。目前所有的 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 grantedor access denit,這是您在 javascript 中測驗的內容
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/428166.html
標籤:javascript php jQuery 阿贾克斯 xmlhttp请求
上一篇:更改影像樣式和標題
