[英]Why does AJAX GET response from PHP have HTML tags?
我的回復文本包含html標簽,這會導致ERROR而不是SUCCESS觸發。 我究竟做錯了什么?
這是我的html代碼:
<head>
<title>HTML Window</title>
<meta charset="UTF-8">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function post() {
var email = document.getElementById("email");
var password = document.getElementById("password");
var data = {
email: email.value,
password: password.value
};
$.ajax({
type: "GET",
url: "http://localhost/ParentChild/index.php",
dataType: "json",
data: data,
success: function (response) {
console.log("SUCCESS");
console.log(response);
},
error: function (response, textStatus, errorThrown) {
console.log("ERROR");
console.log("Status: " + textStatus);
console.log(response.responseText);
}
});
}
</script>
</head>
<body>
<form method="GET" action="javascript:post();">
<div>
Parent Window
<br><label for="email">Email: <input type="text" id="email" name="email"></label>
<br><label for="password">Password: <input type="text" id="password" name="password"></label>
<br><input type="submit" value="Post">
</div>
</form>
</body>
這是我的PHP:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$response = array(
"a" => "test");
echo (json_encode($response);
?>
</body>
</html>
這是控制台消息:
ERROR
(index):28 Status: parsererror
(index):29 errorThrown: SyntaxError: Unexpected token < in JSON at position 0
(index):30 <html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
{"a":"test"} </body>
如果刪除dataType:“ json”,則將觸發SUCCESS,但html標記仍是響應文本的一部分。
我究竟做錯了什么?
將數據返回給ajax調用的PHP腳本應被視為子程序而不是網頁。 如果該腳本中包含HTML,它也將作為總響應的一部分發送回瀏覽器。
因此,將腳本修改為此,即刪除其中包含的所有HTML
<?php
$response = array("a" => "test");
echo (json_encode($response);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.