簡體   English   中英

為什么我的AJAX收到請求失敗

[英]why isn't my AJAX get request working

在我的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>
    <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>

JS: (sample.js)

$(function(){

 $.ajax({
        url : "http://XXXXXX/bn/sample.php",
        type : 'GET',
        data : data,
        dataType : 'json',
        success : function (result) {
           alert(result.ajax); // "Hello world!" should be alerted
           console.log(result.advert); 
        },
        error : function () {
           alert("error");
        }
    });

    });

PHP:

<?php

    $advert = array(
        'ajax' => 'Hello world!',
        'advert' => 'Working',
     );

    echo json_encode($advert);
?>

您在“數據:數據”中設置的數據,以及您發送到php腳本的數據。 但你不發送任何。 成功功能中將提供您收到的數據。 所以打印出來。 再加上我刪除了警報。 警報很la腳。 慰藉!

文檔完全加載后,“ $(document).ready(”部分即會啟動您的功能。我想這就是您需要並想要的。

$(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);
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM