我知道这个问题已经在其他主题中得到了回答,但由于某种原因它对我不起作用,我不明白为什么。
我用 ajax 调用模板,其中设置了一些 php 变量,我需要获取这些 values。
第一个模板。php
<?php
$advert = array(
'ajax' => 'Hello world!',
'advert' => 'Bye',
);
echo json_encode($advert);
?>
第二个模板。php
?>
<script>
jQuery(document).ready(function($){
$.ajax({
beforeSend: function(){
alert('Requesting...');
},
url : 'first-template.php',
type : 'GET',
dataType : 'json',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
alert(result['advert']) // "Bye" alerted
},
error : function(xhr, status, error) {
alert(error);
}
});
});
</script>
这是 https://stackoverflow.com/questions/10341434/get-variable-from-php-file-using-jquery-ajax 的显示方式,但函数返回错误。
回答1
首先,也许,您可以将请求类型更改为 GET,因为您不发布任何内容,而是尝试获取信息。
<script>
jQuery(document).ready(function($){
$.ajax({
beforeSend: function(){
alert('Requesting...');
},
url : 'first-template.php',
type : 'GET',
dataType : 'json',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
alert(result['advert']) // "Bye" alerted
},
error : function () {
alert("error");
}
});
});
</script>
编辑:
这是一个功能脚本:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
$.ajax({
beforeSend: function(){
alert('Requesting...');
},
url : 'first-template.php',
type : 'GET',
dataType : 'json',
success : function (result) {
console.log(result);
},
error : function(xhr, status, error) {
alert(error);
}
});
});
</script>
查看修改:
- GET 而不是 POST
- console.log(result) 查看结果
在我的浏览器控制台中:
Object { ajax: "Hello world!", advert: "Bye" }
可以肯定的是,您是否正确加载了 JQuery 并且您是否在 WAMP/LAMP 服务器上工作?
您可以发布整个文件代码吗?
编辑2:
检查控制台中的错误并将其发布在此处,这更容易在将来找到问题。