Php 为什么不是';我的AJAX请求不能正常工作吗
在我的js页面中,我想使用ajax()从php页面获取一些变量; 这都是由html页面加载触发的。我尝试使用GET和POST,但没有任何警报或日志记录到我的控制台,甚至没有错误 HTML:Php 为什么不是';我的AJAX请求不能正常工作吗,php,jquery,post,get,xmlhttprequest,Php,Jquery,Post,Get,Xmlhttprequest,在我的js页面中,我想使用ajax()从php页面获取一些变量; 这都是由html页面加载触发的。我尝试使用GET和POST,但没有任何警报或日志记录到我的控制台,甚至没有错误 HTML: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script src="http://XXXXXX/bn/sample.js"></script>
</head>
<body>
<div>Welcome! </div>
</body>
</html>
<?php
$advert = array(
'ajax' => 'Hello world!',
'advert' => 'Working',
);
echo json_encode($advert);
?>
PHP:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script src="http://XXXXXX/bn/sample.js"></script>
</head>
<body>
<div>Welcome! </div>
</body>
</html>
<?php
$advert = array(
'ajax' => 'Hello world!',
'advert' => 'Working',
);
echo json_encode($advert);
?>
您在“data:data”设置的数据是您发送到php脚本的数据。但是你不发送任何。您收到的数据在您的成功功能中可用。所以把它打印出来。
而且我删除了警报。警报是站不住脚的。控制台岩石
“$(document).ready”(“part”)在您的文档完全加载后立即启动您的函数。我想这正是您需要和想要的
$(document).ready(function() {
$.ajax({
url : "http://XXXXXX/bn/sample.php",
type : 'GET',
data : (),
dataType : 'json',
success : function (data) {
console.log(data.advert);
},
error : function () {
console.log("error");
}
});
});
编辑:删除最后一个逗号,因为数组到此结束。您可能希望在输出之前设置一个标头
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
$advert = array(
'ajax' => 'Hello world!',
'advert' => 'Working'
);
echo json_encode($advert);
?>
也许您还没有定义数据
呢?更好的办法是,完全删除数据
,因为您似乎没有在PHP文件中使用它。sample.PHP实际输出了什么吗?试着在webbrowser中单独访问sample.PHP。如果您没有看到任何内容或内部服务器错误,那么它就不是您的ajax调用。并检查发生了什么h Chrome控制台或Firebug..您需要解释您所做的事情。您使用的是json文件类型,但用于生成它的文件是php文件。标题告诉您的脚本它正在使用请求的json文件。