希望你们一切都好。事情是这样的。我对 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
?>
然后死掉而不是 echo json 内容
关于javascript - 为什么我的 AJAX 响应包含 HTML 源代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22059270/