[英]Why Does My AJAX Response Contain HTML Source?
希望你們一切都好。 這是交易。 我對PHP進行了AJAX調用,PHP解碼了JSON字符串,然后從json對象回顯了一個屬性,但是在AJAX響應警報中,我從json屬性和當前頁面的源中獲取了正確的值,例如:
jsonProperty<!DOCTYPE HTML>
<html>
<head>... [the rest of the page's source]
這是我的代碼:PHP
<?php
private function validate_review(){
$json = json_decode($_POST['data']);
echo $json->review;
}
?>
AJAX:
<script>
var reviewData = {
title : $('#fieldtitle').val(),
raiting : starRaiting,
review : $('#fieldreview').val()
}
$.ajax({
type: 'post',
url: 'http://localhost/codeigniter/new-review',
data: {data: JSON.stringify(reviewData)},
success: function(result){
alert(result);
}
});
</script>
為什么響應還會包含頁面的來源,這完全是違反直覺和奇怪的。 救命?
指定您的請求數據類型
$.ajax({
type: 'post',
url: 'http://localhost/codeigniter/new-review',
data: {data: JSON.stringify(reviewData)},
dataType: 'jsonp', //tell the server that you expect json
success: function(result){
alert(result);
}
});
<?php
//DO NOT echo any output before header
header('Content-Type: application/json'); //said this response content is json
?>
和死亡,而不是回聲json內容
我認為您的代碼仍包含模板。
private function validate_review(){
$json = json_decode($_POST['data']);
die($json->review);
}
這應該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.