我知道這個問題已經在其他主題中得到了回答,但由于某種原因它對我不起作用,我不明白為什么。
我用 ajax 呼叫模板,里面設定了一些 php 變數,我需要獲取這些值。
第一個模板.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>
這是這里顯示的方式,但函式回傳錯誤。
uj5u.com熱心網友回復:
首先,也許,您可以將請求型別更改為 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:
檢查控制臺中的錯誤并將其發布在此處,這更容易在將來找到問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475379.html
上一篇:jQuery模式彈出不顯示元素值
